Improve of file-local-name use in vc-git-checkin
[emacs.git] / src / eval.c
blobf472efad52eb77cd5787eb3b632a9bfd891ec80c
1 /* Evaluator for GNU Emacs Lisp interpreter.
3 Copyright (C) 1985-1987, 1993-1995, 1999-2017 Free Software Foundation,
4 Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
23 #include <limits.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include "lisp.h"
27 #include "blockinput.h"
28 #include "commands.h"
29 #include "keyboard.h"
30 #include "dispextern.h"
31 #include "buffer.h"
33 /* Chain of condition and catch handlers currently in effect. */
35 /* struct handler *handlerlist; */
37 /* Non-nil means record all fset's and provide's, to be undone
38 if the file being autoloaded is not fully loaded.
39 They are recorded by being consed onto the front of Vautoload_queue:
40 (FUN . ODEF) for a defun, (0 . OFEATURES) for a provide. */
42 Lisp_Object Vautoload_queue;
44 /* This holds either the symbol `run-hooks' or nil.
45 It is nil at an early stage of startup, and when Emacs
46 is shutting down. */
47 Lisp_Object Vrun_hooks;
49 /* The commented-out variables below are macros defined in thread.h. */
51 /* Current number of specbindings allocated in specpdl, not counting
52 the dummy entry specpdl[-1]. */
54 /* ptrdiff_t specpdl_size; */
56 /* Pointer to beginning of specpdl. A dummy entry specpdl[-1] exists
57 only so that its address can be taken. */
59 /* union specbinding *specpdl; */
61 /* Pointer to first unused element in specpdl. */
63 /* union specbinding *specpdl_ptr; */
65 /* Depth in Lisp evaluations and function calls. */
67 /* static EMACS_INT lisp_eval_depth; */
69 /* The value of num_nonmacro_input_events as of the last time we
70 started to enter the debugger. If we decide to enter the debugger
71 again when this is still equal to num_nonmacro_input_events, then we
72 know that the debugger itself has an error, and we should just
73 signal the error instead of entering an infinite loop of debugger
74 invocations. */
76 static EMACS_INT when_entered_debugger;
78 /* The function from which the last `signal' was called. Set in
79 Fsignal. */
80 /* FIXME: We should probably get rid of this! */
81 Lisp_Object Vsignaling_function;
83 /* If non-nil, Lisp code must not be run since some part of Emacs is in
84 an inconsistent state. Currently unused. */
85 Lisp_Object inhibit_lisp_code;
87 /* These would ordinarily be static, but they need to be visible to GDB. */
88 bool backtrace_p (union specbinding *) EXTERNALLY_VISIBLE;
89 Lisp_Object *backtrace_args (union specbinding *) EXTERNALLY_VISIBLE;
90 Lisp_Object backtrace_function (union specbinding *) EXTERNALLY_VISIBLE;
91 union specbinding *backtrace_next (union specbinding *) EXTERNALLY_VISIBLE;
92 union specbinding *backtrace_top (void) EXTERNALLY_VISIBLE;
94 static Lisp_Object funcall_lambda (Lisp_Object, ptrdiff_t, Lisp_Object *);
95 static Lisp_Object apply_lambda (Lisp_Object, Lisp_Object, ptrdiff_t);
96 static Lisp_Object lambda_arity (Lisp_Object);
98 static Lisp_Object
99 specpdl_symbol (union specbinding *pdl)
101 eassert (pdl->kind >= SPECPDL_LET);
102 return pdl->let.symbol;
105 static enum specbind_tag
106 specpdl_kind (union specbinding *pdl)
108 eassert (pdl->kind >= SPECPDL_LET);
109 return pdl->let.kind;
112 static Lisp_Object
113 specpdl_old_value (union specbinding *pdl)
115 eassert (pdl->kind >= SPECPDL_LET);
116 return pdl->let.old_value;
119 static void
120 set_specpdl_old_value (union specbinding *pdl, Lisp_Object val)
122 eassert (pdl->kind >= SPECPDL_LET);
123 pdl->let.old_value = val;
126 static Lisp_Object
127 specpdl_where (union specbinding *pdl)
129 eassert (pdl->kind > SPECPDL_LET);
130 return pdl->let.where;
133 static Lisp_Object
134 specpdl_saved_value (union specbinding *pdl)
136 eassert (pdl->kind >= SPECPDL_LET);
137 return pdl->let.saved_value;
140 static Lisp_Object
141 specpdl_arg (union specbinding *pdl)
143 eassert (pdl->kind == SPECPDL_UNWIND);
144 return pdl->unwind.arg;
147 Lisp_Object
148 backtrace_function (union specbinding *pdl)
150 eassert (pdl->kind == SPECPDL_BACKTRACE);
151 return pdl->bt.function;
154 static ptrdiff_t
155 backtrace_nargs (union specbinding *pdl)
157 eassert (pdl->kind == SPECPDL_BACKTRACE);
158 return pdl->bt.nargs;
161 Lisp_Object *
162 backtrace_args (union specbinding *pdl)
164 eassert (pdl->kind == SPECPDL_BACKTRACE);
165 return pdl->bt.args;
168 static bool
169 backtrace_debug_on_exit (union specbinding *pdl)
171 eassert (pdl->kind == SPECPDL_BACKTRACE);
172 return pdl->bt.debug_on_exit;
175 /* Functions to modify slots of backtrace records. */
177 static void
178 set_backtrace_args (union specbinding *pdl, Lisp_Object *args, ptrdiff_t nargs)
180 eassert (pdl->kind == SPECPDL_BACKTRACE);
181 pdl->bt.args = args;
182 pdl->bt.nargs = nargs;
185 static void
186 set_backtrace_debug_on_exit (union specbinding *pdl, bool doe)
188 eassert (pdl->kind == SPECPDL_BACKTRACE);
189 pdl->bt.debug_on_exit = doe;
192 /* Helper functions to scan the backtrace. */
194 bool
195 backtrace_p (union specbinding *pdl)
196 { return pdl >= specpdl; }
198 union specbinding *
199 backtrace_top (void)
201 union specbinding *pdl = specpdl_ptr - 1;
202 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
203 pdl--;
204 return pdl;
207 union specbinding *
208 backtrace_next (union specbinding *pdl)
210 pdl--;
211 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
212 pdl--;
213 return pdl;
216 /* Return a pointer to somewhere near the top of the C stack. */
217 void *
218 near_C_stack_top (void)
220 return backtrace_args (backtrace_top ());
223 void
224 init_eval_once (void)
226 enum { size = 50 };
227 union specbinding *pdlvec = xmalloc ((size + 1) * sizeof *specpdl);
228 specpdl_size = size;
229 specpdl = specpdl_ptr = pdlvec + 1;
230 /* Don't forget to update docs (lispref node "Local Variables"). */
231 max_specpdl_size = 1300; /* 1000 is not enough for CEDET's c-by.el. */
232 max_lisp_eval_depth = 800;
234 Vrun_hooks = Qnil;
237 /* static struct handler handlerlist_sentinel; */
239 void
240 init_eval (void)
242 specpdl_ptr = specpdl;
243 { /* Put a dummy catcher at top-level so that handlerlist is never NULL.
244 This is important since handlerlist->nextfree holds the freelist
245 which would otherwise leak every time we unwind back to top-level. */
246 handlerlist_sentinel = xzalloc (sizeof (struct handler));
247 handlerlist = handlerlist_sentinel->nextfree = handlerlist_sentinel;
248 struct handler *c = push_handler (Qunbound, CATCHER);
249 eassert (c == handlerlist_sentinel);
250 handlerlist_sentinel->nextfree = NULL;
251 handlerlist_sentinel->next = NULL;
253 Vquit_flag = Qnil;
254 debug_on_next_call = 0;
255 lisp_eval_depth = 0;
256 /* This is less than the initial value of num_nonmacro_input_events. */
257 when_entered_debugger = -1;
260 /* Unwind-protect function used by call_debugger. */
262 static void
263 restore_stack_limits (Lisp_Object data)
265 max_specpdl_size = XINT (XCAR (data));
266 max_lisp_eval_depth = XINT (XCDR (data));
269 static void grow_specpdl (void);
271 /* Call the Lisp debugger, giving it argument ARG. */
273 Lisp_Object
274 call_debugger (Lisp_Object arg)
276 bool debug_while_redisplaying;
277 ptrdiff_t count = SPECPDL_INDEX ();
278 Lisp_Object val;
279 EMACS_INT old_depth = max_lisp_eval_depth;
280 /* Do not allow max_specpdl_size less than actual depth (Bug#16603). */
281 EMACS_INT old_max = max (max_specpdl_size, count);
283 if (lisp_eval_depth + 40 > max_lisp_eval_depth)
284 max_lisp_eval_depth = lisp_eval_depth + 40;
286 /* While debugging Bug#16603, previous value of 100 was found
287 too small to avoid specpdl overflow in the debugger itself. */
288 if (max_specpdl_size - 200 < count)
289 max_specpdl_size = count + 200;
291 if (old_max == count)
293 /* We can enter the debugger due to specpdl overflow (Bug#16603). */
294 specpdl_ptr--;
295 grow_specpdl ();
298 /* Restore limits after leaving the debugger. */
299 record_unwind_protect (restore_stack_limits,
300 Fcons (make_number (old_max),
301 make_number (old_depth)));
303 #ifdef HAVE_WINDOW_SYSTEM
304 if (display_hourglass_p)
305 cancel_hourglass ();
306 #endif
308 debug_on_next_call = 0;
309 when_entered_debugger = num_nonmacro_input_events;
311 /* Resetting redisplaying_p to 0 makes sure that debug output is
312 displayed if the debugger is invoked during redisplay. */
313 debug_while_redisplaying = redisplaying_p;
314 redisplaying_p = 0;
315 specbind (intern ("debugger-may-continue"),
316 debug_while_redisplaying ? Qnil : Qt);
317 specbind (Qinhibit_redisplay, Qnil);
318 specbind (Qinhibit_debugger, Qt);
320 /* If we are debugging an error while `inhibit-changing-match-data'
321 is bound to non-nil (e.g., within a call to `string-match-p'),
322 then make sure debugger code can still use match data. */
323 specbind (Qinhibit_changing_match_data, Qnil);
325 #if 0 /* Binding this prevents execution of Lisp code during
326 redisplay, which necessarily leads to display problems. */
327 specbind (Qinhibit_eval_during_redisplay, Qt);
328 #endif
330 val = apply1 (Vdebugger, arg);
332 /* Interrupting redisplay and resuming it later is not safe under
333 all circumstances. So, when the debugger returns, abort the
334 interrupted redisplay by going back to the top-level. */
335 if (debug_while_redisplaying)
336 Ftop_level ();
338 return unbind_to (count, val);
341 static void
342 do_debug_on_call (Lisp_Object code, ptrdiff_t count)
344 debug_on_next_call = 0;
345 set_backtrace_debug_on_exit (specpdl + count, true);
346 call_debugger (list1 (code));
349 /* NOTE!!! Every function that can call EVAL must protect its args
350 and temporaries from garbage collection while it needs them.
351 The definition of `For' shows what you have to do. */
353 DEFUN ("or", For, Sor, 0, UNEVALLED, 0,
354 doc: /* Eval args until one of them yields non-nil, then return that value.
355 The remaining args are not evalled at all.
356 If all args return nil, return nil.
357 usage: (or CONDITIONS...) */)
358 (Lisp_Object args)
360 Lisp_Object val = Qnil;
362 while (CONSP (args))
364 val = eval_sub (XCAR (args));
365 if (!NILP (val))
366 break;
367 args = XCDR (args);
370 return val;
373 DEFUN ("and", Fand, Sand, 0, UNEVALLED, 0,
374 doc: /* Eval args until one of them yields nil, then return nil.
375 The remaining args are not evalled at all.
376 If no arg yields nil, return the last arg's value.
377 usage: (and CONDITIONS...) */)
378 (Lisp_Object args)
380 Lisp_Object val = Qt;
382 while (CONSP (args))
384 val = eval_sub (XCAR (args));
385 if (NILP (val))
386 break;
387 args = XCDR (args);
390 return val;
393 DEFUN ("if", Fif, Sif, 2, UNEVALLED, 0,
394 doc: /* If COND yields non-nil, do THEN, else do ELSE...
395 Returns the value of THEN or the value of the last of the ELSE's.
396 THEN must be one expression, but ELSE... can be zero or more expressions.
397 If COND yields nil, and there are no ELSE's, the value is nil.
398 usage: (if COND THEN ELSE...) */)
399 (Lisp_Object args)
401 Lisp_Object cond;
403 cond = eval_sub (XCAR (args));
405 if (!NILP (cond))
406 return eval_sub (Fcar (XCDR (args)));
407 return Fprogn (XCDR (XCDR (args)));
410 DEFUN ("cond", Fcond, Scond, 0, UNEVALLED, 0,
411 doc: /* Try each clause until one succeeds.
412 Each clause looks like (CONDITION BODY...). CONDITION is evaluated
413 and, if the value is non-nil, this clause succeeds:
414 then the expressions in BODY are evaluated and the last one's
415 value is the value of the cond-form.
416 If a clause has one element, as in (CONDITION), then the cond-form
417 returns CONDITION's value, if that is non-nil.
418 If no clause succeeds, cond returns nil.
419 usage: (cond CLAUSES...) */)
420 (Lisp_Object args)
422 Lisp_Object val = args;
424 while (CONSP (args))
426 Lisp_Object clause = XCAR (args);
427 val = eval_sub (Fcar (clause));
428 if (!NILP (val))
430 if (!NILP (XCDR (clause)))
431 val = Fprogn (XCDR (clause));
432 break;
434 args = XCDR (args);
437 return val;
440 DEFUN ("progn", Fprogn, Sprogn, 0, UNEVALLED, 0,
441 doc: /* Eval BODY forms sequentially and return value of last one.
442 usage: (progn BODY...) */)
443 (Lisp_Object body)
445 Lisp_Object val = Qnil;
447 while (CONSP (body))
449 val = eval_sub (XCAR (body));
450 body = XCDR (body);
453 return val;
456 /* Evaluate BODY sequentially, discarding its value. */
458 void
459 prog_ignore (Lisp_Object body)
461 Fprogn (body);
464 DEFUN ("prog1", Fprog1, Sprog1, 1, UNEVALLED, 0,
465 doc: /* Eval FIRST and BODY sequentially; return value from FIRST.
466 The value of FIRST is saved during the evaluation of the remaining args,
467 whose values are discarded.
468 usage: (prog1 FIRST BODY...) */)
469 (Lisp_Object args)
471 Lisp_Object val = eval_sub (XCAR (args));
472 prog_ignore (XCDR (args));
473 return val;
476 DEFUN ("prog2", Fprog2, Sprog2, 2, UNEVALLED, 0,
477 doc: /* Eval FORM1, FORM2 and BODY sequentially; return value from FORM2.
478 The value of FORM2 is saved during the evaluation of the
479 remaining args, whose values are discarded.
480 usage: (prog2 FORM1 FORM2 BODY...) */)
481 (Lisp_Object args)
483 eval_sub (XCAR (args));
484 return Fprog1 (XCDR (args));
487 DEFUN ("setq", Fsetq, Ssetq, 0, UNEVALLED, 0,
488 doc: /* Set each SYM to the value of its VAL.
489 The symbols SYM are variables; they are literal (not evaluated).
490 The values VAL are expressions; they are evaluated.
491 Thus, (setq x (1+ y)) sets `x' to the value of `(1+ y)'.
492 The second VAL is not computed until after the first SYM is set, and so on;
493 each VAL can use the new value of variables set earlier in the `setq'.
494 The return value of the `setq' form is the value of the last VAL.
495 usage: (setq [SYM VAL]...) */)
496 (Lisp_Object args)
498 Lisp_Object val, sym, lex_binding;
500 val = args;
501 if (CONSP (args))
503 Lisp_Object args_left = args;
504 Lisp_Object numargs = Flength (args);
506 if (XINT (numargs) & 1)
507 xsignal2 (Qwrong_number_of_arguments, Qsetq, numargs);
511 val = eval_sub (Fcar (XCDR (args_left)));
512 sym = XCAR (args_left);
514 /* Like for eval_sub, we do not check declared_special here since
515 it's been done when let-binding. */
516 if (!NILP (Vinternal_interpreter_environment) /* Mere optimization! */
517 && SYMBOLP (sym)
518 && !NILP (lex_binding
519 = Fassq (sym, Vinternal_interpreter_environment)))
520 XSETCDR (lex_binding, val); /* SYM is lexically bound. */
521 else
522 Fset (sym, val); /* SYM is dynamically bound. */
524 args_left = Fcdr (XCDR (args_left));
526 while (CONSP (args_left));
529 return val;
532 DEFUN ("quote", Fquote, Squote, 1, UNEVALLED, 0,
533 doc: /* Return the argument, without evaluating it. `(quote x)' yields `x'.
534 Warning: `quote' does not construct its return value, but just returns
535 the value that was pre-constructed by the Lisp reader (see info node
536 `(elisp)Printed Representation').
537 This means that \\='(a . b) is not identical to (cons \\='a \\='b): the former
538 does not cons. Quoting should be reserved for constants that will
539 never be modified by side-effects, unless you like self-modifying code.
540 See the common pitfall in info node `(elisp)Rearrangement' for an example
541 of unexpected results when a quoted object is modified.
542 usage: (quote ARG) */)
543 (Lisp_Object args)
545 if (CONSP (XCDR (args)))
546 xsignal2 (Qwrong_number_of_arguments, Qquote, Flength (args));
547 return XCAR (args);
550 DEFUN ("function", Ffunction, Sfunction, 1, UNEVALLED, 0,
551 doc: /* Like `quote', but preferred for objects which are functions.
552 In byte compilation, `function' causes its argument to be compiled.
553 `quote' cannot do that.
554 usage: (function ARG) */)
555 (Lisp_Object args)
557 Lisp_Object quoted = XCAR (args);
559 if (CONSP (XCDR (args)))
560 xsignal2 (Qwrong_number_of_arguments, Qfunction, Flength (args));
562 if (!NILP (Vinternal_interpreter_environment)
563 && CONSP (quoted)
564 && EQ (XCAR (quoted), Qlambda))
565 { /* This is a lambda expression within a lexical environment;
566 return an interpreted closure instead of a simple lambda. */
567 Lisp_Object cdr = XCDR (quoted);
568 Lisp_Object tmp = cdr;
569 if (CONSP (tmp)
570 && (tmp = XCDR (tmp), CONSP (tmp))
571 && (tmp = XCAR (tmp), CONSP (tmp))
572 && (EQ (QCdocumentation, XCAR (tmp))))
573 { /* Handle the special (:documentation <form>) to build the docstring
574 dynamically. */
575 Lisp_Object docstring = eval_sub (Fcar (XCDR (tmp)));
576 CHECK_STRING (docstring);
577 cdr = Fcons (XCAR (cdr), Fcons (docstring, XCDR (XCDR (cdr))));
579 return Fcons (Qclosure, Fcons (Vinternal_interpreter_environment,
580 cdr));
582 else
583 /* Simply quote the argument. */
584 return quoted;
588 DEFUN ("defvaralias", Fdefvaralias, Sdefvaralias, 2, 3, 0,
589 doc: /* Make NEW-ALIAS a variable alias for symbol BASE-VARIABLE.
590 Aliased variables always have the same value; setting one sets the other.
591 Third arg DOCSTRING, if non-nil, is documentation for NEW-ALIAS. If it is
592 omitted or nil, NEW-ALIAS gets the documentation string of BASE-VARIABLE,
593 or of the variable at the end of the chain of aliases, if BASE-VARIABLE is
594 itself an alias. If NEW-ALIAS is bound, and BASE-VARIABLE is not,
595 then the value of BASE-VARIABLE is set to that of NEW-ALIAS.
596 The return value is BASE-VARIABLE. */)
597 (Lisp_Object new_alias, Lisp_Object base_variable, Lisp_Object docstring)
599 struct Lisp_Symbol *sym;
601 CHECK_SYMBOL (new_alias);
602 CHECK_SYMBOL (base_variable);
604 if (SYMBOL_CONSTANT_P (new_alias))
605 /* Making it an alias effectively changes its value. */
606 error ("Cannot make a constant an alias");
608 sym = XSYMBOL (new_alias);
610 switch (sym->redirect)
612 case SYMBOL_FORWARDED:
613 error ("Cannot make an internal variable an alias");
614 case SYMBOL_LOCALIZED:
615 error ("Don't know how to make a localized variable an alias");
616 case SYMBOL_PLAINVAL:
617 case SYMBOL_VARALIAS:
618 break;
619 default:
620 emacs_abort ();
623 /* http://lists.gnu.org/archive/html/emacs-devel/2008-04/msg00834.html
624 If n_a is bound, but b_v is not, set the value of b_v to n_a,
625 so that old-code that affects n_a before the aliasing is setup
626 still works. */
627 if (NILP (Fboundp (base_variable)))
628 set_internal (base_variable, find_symbol_value (new_alias),
629 Qnil, SET_INTERNAL_BIND);
631 union specbinding *p;
633 for (p = specpdl_ptr; p > specpdl; )
634 if ((--p)->kind >= SPECPDL_LET
635 && (EQ (new_alias, specpdl_symbol (p))))
636 error ("Don't know how to make a let-bound variable an alias");
639 if (sym->trapped_write == SYMBOL_TRAPPED_WRITE)
640 notify_variable_watchers (new_alias, base_variable, Qdefvaralias, Qnil);
642 sym->declared_special = 1;
643 XSYMBOL (base_variable)->declared_special = 1;
644 sym->redirect = SYMBOL_VARALIAS;
645 SET_SYMBOL_ALIAS (sym, XSYMBOL (base_variable));
646 sym->trapped_write = XSYMBOL (base_variable)->trapped_write;
647 LOADHIST_ATTACH (new_alias);
648 /* Even if docstring is nil: remove old docstring. */
649 Fput (new_alias, Qvariable_documentation, docstring);
651 return base_variable;
654 static union specbinding *
655 default_toplevel_binding (Lisp_Object symbol)
657 union specbinding *binding = NULL;
658 union specbinding *pdl = specpdl_ptr;
659 while (pdl > specpdl)
661 switch ((--pdl)->kind)
663 case SPECPDL_LET_DEFAULT:
664 case SPECPDL_LET:
665 if (EQ (specpdl_symbol (pdl), symbol))
666 binding = pdl;
667 break;
669 case SPECPDL_UNWIND:
670 case SPECPDL_UNWIND_PTR:
671 case SPECPDL_UNWIND_INT:
672 case SPECPDL_UNWIND_VOID:
673 case SPECPDL_BACKTRACE:
674 case SPECPDL_LET_LOCAL:
675 break;
677 default:
678 emacs_abort ();
681 return binding;
684 DEFUN ("default-toplevel-value", Fdefault_toplevel_value, Sdefault_toplevel_value, 1, 1, 0,
685 doc: /* Return SYMBOL's toplevel default value.
686 "Toplevel" means outside of any let binding. */)
687 (Lisp_Object symbol)
689 union specbinding *binding = default_toplevel_binding (symbol);
690 Lisp_Object value
691 = binding ? specpdl_old_value (binding) : Fdefault_value (symbol);
692 if (!EQ (value, Qunbound))
693 return value;
694 xsignal1 (Qvoid_variable, symbol);
697 DEFUN ("set-default-toplevel-value", Fset_default_toplevel_value,
698 Sset_default_toplevel_value, 2, 2, 0,
699 doc: /* Set SYMBOL's toplevel default value to VALUE.
700 "Toplevel" means outside of any let binding. */)
701 (Lisp_Object symbol, Lisp_Object value)
703 union specbinding *binding = default_toplevel_binding (symbol);
704 if (binding)
705 set_specpdl_old_value (binding, value);
706 else
707 Fset_default (symbol, value);
708 return Qnil;
711 DEFUN ("defvar", Fdefvar, Sdefvar, 1, UNEVALLED, 0,
712 doc: /* Define SYMBOL as a variable, and return SYMBOL.
713 You are not required to define a variable in order to use it, but
714 defining it lets you supply an initial value and documentation, which
715 can be referred to by the Emacs help facilities and other programming
716 tools. The `defvar' form also declares the variable as \"special\",
717 so that it is always dynamically bound even if `lexical-binding' is t.
719 If SYMBOL's value is void and the optional argument INITVALUE is
720 provided, INITVALUE is evaluated and the result used to set SYMBOL's
721 value. If SYMBOL is buffer-local, its default value is what is set;
722 buffer-local values are not affected. If INITVALUE is missing,
723 SYMBOL's value is not set.
725 If SYMBOL has a local binding, then this form affects the local
726 binding. This is usually not what you want. Thus, if you need to
727 load a file defining variables, with this form or with `defconst' or
728 `defcustom', you should always load that file _outside_ any bindings
729 for these variables. (`defconst' and `defcustom' behave similarly in
730 this respect.)
732 The optional argument DOCSTRING is a documentation string for the
733 variable.
735 To define a user option, use `defcustom' instead of `defvar'.
736 usage: (defvar SYMBOL &optional INITVALUE DOCSTRING) */)
737 (Lisp_Object args)
739 Lisp_Object sym, tem, tail;
741 sym = XCAR (args);
742 tail = XCDR (args);
744 if (CONSP (tail))
746 if (CONSP (XCDR (tail)) && CONSP (XCDR (XCDR (tail))))
747 error ("Too many arguments");
749 tem = Fdefault_boundp (sym);
751 /* Do it before evaluating the initial value, for self-references. */
752 XSYMBOL (sym)->declared_special = 1;
754 if (NILP (tem))
755 Fset_default (sym, eval_sub (XCAR (tail)));
756 else
757 { /* Check if there is really a global binding rather than just a let
758 binding that shadows the global unboundness of the var. */
759 union specbinding *binding = default_toplevel_binding (sym);
760 if (binding && EQ (specpdl_old_value (binding), Qunbound))
762 set_specpdl_old_value (binding, eval_sub (XCAR (tail)));
765 tail = XCDR (tail);
766 tem = Fcar (tail);
767 if (!NILP (tem))
769 if (!NILP (Vpurify_flag))
770 tem = Fpurecopy (tem);
771 Fput (sym, Qvariable_documentation, tem);
773 LOADHIST_ATTACH (sym);
775 else if (!NILP (Vinternal_interpreter_environment)
776 && !XSYMBOL (sym)->declared_special)
777 /* A simple (defvar foo) with lexical scoping does "nothing" except
778 declare that var to be dynamically scoped *locally* (i.e. within
779 the current file or let-block). */
780 Vinternal_interpreter_environment
781 = Fcons (sym, Vinternal_interpreter_environment);
782 else
784 /* Simple (defvar <var>) should not count as a definition at all.
785 It could get in the way of other definitions, and unloading this
786 package could try to make the variable unbound. */
789 return sym;
792 DEFUN ("defconst", Fdefconst, Sdefconst, 2, UNEVALLED, 0,
793 doc: /* Define SYMBOL as a constant variable.
794 This declares that neither programs nor users should ever change the
795 value. This constancy is not actually enforced by Emacs Lisp, but
796 SYMBOL is marked as a special variable so that it is never lexically
797 bound.
799 The `defconst' form always sets the value of SYMBOL to the result of
800 evalling INITVALUE. If SYMBOL is buffer-local, its default value is
801 what is set; buffer-local values are not affected. If SYMBOL has a
802 local binding, then this form sets the local binding's value.
803 However, you should normally not make local bindings for variables
804 defined with this form.
806 The optional DOCSTRING specifies the variable's documentation string.
807 usage: (defconst SYMBOL INITVALUE [DOCSTRING]) */)
808 (Lisp_Object args)
810 Lisp_Object sym, tem;
812 sym = XCAR (args);
813 if (CONSP (Fcdr (XCDR (XCDR (args)))))
814 error ("Too many arguments");
816 tem = eval_sub (Fcar (XCDR (args)));
817 if (!NILP (Vpurify_flag))
818 tem = Fpurecopy (tem);
819 Fset_default (sym, tem);
820 XSYMBOL (sym)->declared_special = 1;
821 tem = Fcar (XCDR (XCDR (args)));
822 if (!NILP (tem))
824 if (!NILP (Vpurify_flag))
825 tem = Fpurecopy (tem);
826 Fput (sym, Qvariable_documentation, tem);
828 Fput (sym, Qrisky_local_variable, Qt);
829 LOADHIST_ATTACH (sym);
830 return sym;
833 /* Make SYMBOL lexically scoped. */
834 DEFUN ("internal-make-var-non-special", Fmake_var_non_special,
835 Smake_var_non_special, 1, 1, 0,
836 doc: /* Internal function. */)
837 (Lisp_Object symbol)
839 CHECK_SYMBOL (symbol);
840 XSYMBOL (symbol)->declared_special = 0;
841 return Qnil;
845 DEFUN ("let*", FletX, SletX, 1, UNEVALLED, 0,
846 doc: /* Bind variables according to VARLIST then eval BODY.
847 The value of the last form in BODY is returned.
848 Each element of VARLIST is a symbol (which is bound to nil)
849 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
850 Each VALUEFORM can refer to the symbols already bound by this VARLIST.
851 usage: (let* VARLIST BODY...) */)
852 (Lisp_Object args)
854 Lisp_Object varlist, var, val, elt, lexenv;
855 ptrdiff_t count = SPECPDL_INDEX ();
857 lexenv = Vinternal_interpreter_environment;
859 for (varlist = XCAR (args); CONSP (varlist); varlist = XCDR (varlist))
861 maybe_quit ();
863 elt = XCAR (varlist);
864 if (SYMBOLP (elt))
866 var = elt;
867 val = Qnil;
869 else if (! NILP (Fcdr (Fcdr (elt))))
870 signal_error ("`let' bindings can have only one value-form", elt);
871 else
873 var = Fcar (elt);
874 val = eval_sub (Fcar (Fcdr (elt)));
877 if (!NILP (lexenv) && SYMBOLP (var)
878 && !XSYMBOL (var)->declared_special
879 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
880 /* Lexically bind VAR by adding it to the interpreter's binding
881 alist. */
883 Lisp_Object newenv
884 = Fcons (Fcons (var, val), Vinternal_interpreter_environment);
885 if (EQ (Vinternal_interpreter_environment, lexenv))
886 /* Save the old lexical environment on the specpdl stack,
887 but only for the first lexical binding, since we'll never
888 need to revert to one of the intermediate ones. */
889 specbind (Qinternal_interpreter_environment, newenv);
890 else
891 Vinternal_interpreter_environment = newenv;
893 else
894 specbind (var, val);
896 CHECK_LIST_END (varlist, XCAR (args));
898 val = Fprogn (XCDR (args));
899 return unbind_to (count, val);
902 DEFUN ("let", Flet, Slet, 1, UNEVALLED, 0,
903 doc: /* Bind variables according to VARLIST then eval BODY.
904 The value of the last form in BODY is returned.
905 Each element of VARLIST is a symbol (which is bound to nil)
906 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
907 All the VALUEFORMs are evalled before any symbols are bound.
908 usage: (let VARLIST BODY...) */)
909 (Lisp_Object args)
911 Lisp_Object *temps, tem, lexenv;
912 Lisp_Object elt, varlist;
913 ptrdiff_t count = SPECPDL_INDEX ();
914 ptrdiff_t argnum;
915 USE_SAFE_ALLOCA;
917 varlist = XCAR (args);
918 CHECK_LIST (varlist);
920 /* Make space to hold the values to give the bound variables. */
921 elt = Flength (varlist);
922 SAFE_ALLOCA_LISP (temps, XFASTINT (elt));
924 /* Compute the values and store them in `temps'. */
926 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
928 maybe_quit ();
929 elt = XCAR (varlist);
930 if (SYMBOLP (elt))
931 temps [argnum++] = Qnil;
932 else if (! NILP (Fcdr (Fcdr (elt))))
933 signal_error ("`let' bindings can have only one value-form", elt);
934 else
935 temps [argnum++] = eval_sub (Fcar (Fcdr (elt)));
938 lexenv = Vinternal_interpreter_environment;
940 varlist = XCAR (args);
941 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
943 Lisp_Object var;
945 elt = XCAR (varlist);
946 var = SYMBOLP (elt) ? elt : Fcar (elt);
947 tem = temps[argnum++];
949 if (!NILP (lexenv) && SYMBOLP (var)
950 && !XSYMBOL (var)->declared_special
951 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
952 /* Lexically bind VAR by adding it to the lexenv alist. */
953 lexenv = Fcons (Fcons (var, tem), lexenv);
954 else
955 /* Dynamically bind VAR. */
956 specbind (var, tem);
959 if (!EQ (lexenv, Vinternal_interpreter_environment))
960 /* Instantiate a new lexical environment. */
961 specbind (Qinternal_interpreter_environment, lexenv);
963 elt = Fprogn (XCDR (args));
964 SAFE_FREE ();
965 return unbind_to (count, elt);
968 DEFUN ("while", Fwhile, Swhile, 1, UNEVALLED, 0,
969 doc: /* If TEST yields non-nil, eval BODY... and repeat.
970 The order of execution is thus TEST, BODY, TEST, BODY and so on
971 until TEST returns nil.
972 usage: (while TEST BODY...) */)
973 (Lisp_Object args)
975 Lisp_Object test, body;
977 test = XCAR (args);
978 body = XCDR (args);
979 while (!NILP (eval_sub (test)))
981 maybe_quit ();
982 prog_ignore (body);
985 return Qnil;
988 DEFUN ("macroexpand", Fmacroexpand, Smacroexpand, 1, 2, 0,
989 doc: /* Return result of expanding macros at top level of FORM.
990 If FORM is not a macro call, it is returned unchanged.
991 Otherwise, the macro is expanded and the expansion is considered
992 in place of FORM. When a non-macro-call results, it is returned.
994 The second optional arg ENVIRONMENT specifies an environment of macro
995 definitions to shadow the loaded ones for use in file byte-compilation. */)
996 (Lisp_Object form, Lisp_Object environment)
998 /* With cleanups from Hallvard Furuseth. */
999 register Lisp_Object expander, sym, def, tem;
1001 while (1)
1003 /* Come back here each time we expand a macro call,
1004 in case it expands into another macro call. */
1005 if (!CONSP (form))
1006 break;
1007 /* Set SYM, give DEF and TEM right values in case SYM is not a symbol. */
1008 def = sym = XCAR (form);
1009 tem = Qnil;
1010 /* Trace symbols aliases to other symbols
1011 until we get a symbol that is not an alias. */
1012 while (SYMBOLP (def))
1014 maybe_quit ();
1015 sym = def;
1016 tem = Fassq (sym, environment);
1017 if (NILP (tem))
1019 def = XSYMBOL (sym)->function;
1020 if (!NILP (def))
1021 continue;
1023 break;
1025 /* Right now TEM is the result from SYM in ENVIRONMENT,
1026 and if TEM is nil then DEF is SYM's function definition. */
1027 if (NILP (tem))
1029 /* SYM is not mentioned in ENVIRONMENT.
1030 Look at its function definition. */
1031 def = Fautoload_do_load (def, sym, Qmacro);
1032 if (!CONSP (def))
1033 /* Not defined or definition not suitable. */
1034 break;
1035 if (!EQ (XCAR (def), Qmacro))
1036 break;
1037 else expander = XCDR (def);
1039 else
1041 expander = XCDR (tem);
1042 if (NILP (expander))
1043 break;
1046 Lisp_Object newform = apply1 (expander, XCDR (form));
1047 if (EQ (form, newform))
1048 break;
1049 else
1050 form = newform;
1053 return form;
1056 DEFUN ("catch", Fcatch, Scatch, 1, UNEVALLED, 0,
1057 doc: /* Eval BODY allowing nonlocal exits using `throw'.
1058 TAG is evalled to get the tag to use; it must not be nil.
1060 Then the BODY is executed.
1061 Within BODY, a call to `throw' with the same TAG exits BODY and this `catch'.
1062 If no throw happens, `catch' returns the value of the last BODY form.
1063 If a throw happens, it specifies the value to return from `catch'.
1064 usage: (catch TAG BODY...) */)
1065 (Lisp_Object args)
1067 Lisp_Object tag = eval_sub (XCAR (args));
1068 return internal_catch (tag, Fprogn, XCDR (args));
1071 /* Assert that E is true, but do not evaluate E. Use this instead of
1072 eassert (E) when E contains variables that might be clobbered by a
1073 longjmp. */
1075 #define clobbered_eassert(E) verify (sizeof (E) != 0)
1077 /* Set up a catch, then call C function FUNC on argument ARG.
1078 FUNC should return a Lisp_Object.
1079 This is how catches are done from within C code. */
1081 Lisp_Object
1082 internal_catch (Lisp_Object tag,
1083 Lisp_Object (*func) (Lisp_Object), Lisp_Object arg)
1085 /* This structure is made part of the chain `catchlist'. */
1086 struct handler *c = push_handler (tag, CATCHER);
1088 /* Call FUNC. */
1089 if (! sys_setjmp (c->jmp))
1091 Lisp_Object val = func (arg);
1092 eassert (handlerlist == c);
1093 handlerlist = c->next;
1094 return val;
1096 else
1097 { /* Throw works by a longjmp that comes right here. */
1098 Lisp_Object val = handlerlist->val;
1099 clobbered_eassert (handlerlist == c);
1100 handlerlist = handlerlist->next;
1101 return val;
1105 /* Unwind the specbind, catch, and handler stacks back to CATCH, and
1106 jump to that CATCH, returning VALUE as the value of that catch.
1108 This is the guts of Fthrow and Fsignal; they differ only in the way
1109 they choose the catch tag to throw to. A catch tag for a
1110 condition-case form has a TAG of Qnil.
1112 Before each catch is discarded, unbind all special bindings and
1113 execute all unwind-protect clauses made above that catch. Unwind
1114 the handler stack as we go, so that the proper handlers are in
1115 effect for each unwind-protect clause we run. At the end, restore
1116 some static info saved in CATCH, and longjmp to the location
1117 specified there.
1119 This is used for correct unwinding in Fthrow and Fsignal. */
1121 static _Noreturn void
1122 unwind_to_catch (struct handler *catch, Lisp_Object value)
1124 bool last_time;
1126 eassert (catch->next);
1128 /* Save the value in the tag. */
1129 catch->val = value;
1131 /* Restore certain special C variables. */
1132 set_poll_suppress_count (catch->poll_suppress_count);
1133 unblock_input_to (catch->interrupt_input_blocked);
1137 /* Unwind the specpdl stack, and then restore the proper set of
1138 handlers. */
1139 unbind_to (handlerlist->pdlcount, Qnil);
1140 last_time = handlerlist == catch;
1141 if (! last_time)
1142 handlerlist = handlerlist->next;
1144 while (! last_time);
1146 eassert (handlerlist == catch);
1148 lisp_eval_depth = catch->f_lisp_eval_depth;
1150 sys_longjmp (catch->jmp, 1);
1153 DEFUN ("throw", Fthrow, Sthrow, 2, 2, 0,
1154 doc: /* Throw to the catch for TAG and return VALUE from it.
1155 Both TAG and VALUE are evalled. */
1156 attributes: noreturn)
1157 (register Lisp_Object tag, Lisp_Object value)
1159 struct handler *c;
1161 if (!NILP (tag))
1162 for (c = handlerlist; c; c = c->next)
1164 if (c->type == CATCHER_ALL)
1165 unwind_to_catch (c, Fcons (tag, value));
1166 if (c->type == CATCHER && EQ (c->tag_or_ch, tag))
1167 unwind_to_catch (c, value);
1169 xsignal2 (Qno_catch, tag, value);
1173 DEFUN ("unwind-protect", Funwind_protect, Sunwind_protect, 1, UNEVALLED, 0,
1174 doc: /* Do BODYFORM, protecting with UNWINDFORMS.
1175 If BODYFORM completes normally, its value is returned
1176 after executing the UNWINDFORMS.
1177 If BODYFORM exits nonlocally, the UNWINDFORMS are executed anyway.
1178 usage: (unwind-protect BODYFORM UNWINDFORMS...) */)
1179 (Lisp_Object args)
1181 Lisp_Object val;
1182 ptrdiff_t count = SPECPDL_INDEX ();
1184 record_unwind_protect (prog_ignore, XCDR (args));
1185 val = eval_sub (XCAR (args));
1186 return unbind_to (count, val);
1189 DEFUN ("condition-case", Fcondition_case, Scondition_case, 2, UNEVALLED, 0,
1190 doc: /* Regain control when an error is signaled.
1191 Executes BODYFORM and returns its value if no error happens.
1192 Each element of HANDLERS looks like (CONDITION-NAME BODY...)
1193 where the BODY is made of Lisp expressions.
1195 A handler is applicable to an error
1196 if CONDITION-NAME is one of the error's condition names.
1197 If an error happens, the first applicable handler is run.
1199 The car of a handler may be a list of condition names instead of a
1200 single condition name; then it handles all of them. If the special
1201 condition name `debug' is present in this list, it allows another
1202 condition in the list to run the debugger if `debug-on-error' and the
1203 other usual mechanisms says it should (otherwise, `condition-case'
1204 suppresses the debugger).
1206 When a handler handles an error, control returns to the `condition-case'
1207 and it executes the handler's BODY...
1208 with VAR bound to (ERROR-SYMBOL . SIGNAL-DATA) from the error.
1209 \(If VAR is nil, the handler can't access that information.)
1210 Then the value of the last BODY form is returned from the `condition-case'
1211 expression.
1213 See also the function `signal' for more info.
1214 usage: (condition-case VAR BODYFORM &rest HANDLERS) */)
1215 (Lisp_Object args)
1217 Lisp_Object var = XCAR (args);
1218 Lisp_Object bodyform = XCAR (XCDR (args));
1219 Lisp_Object handlers = XCDR (XCDR (args));
1221 return internal_lisp_condition_case (var, bodyform, handlers);
1224 /* Like Fcondition_case, but the args are separate
1225 rather than passed in a list. Used by Fbyte_code. */
1227 Lisp_Object
1228 internal_lisp_condition_case (Lisp_Object var, Lisp_Object bodyform,
1229 Lisp_Object handlers)
1231 struct handler *oldhandlerlist = handlerlist;
1232 ptrdiff_t clausenb = 0;
1234 CHECK_SYMBOL (var);
1236 for (Lisp_Object tail = handlers; CONSP (tail); tail = XCDR (tail))
1238 Lisp_Object tem = XCAR (tail);
1239 clausenb++;
1240 if (! (NILP (tem)
1241 || (CONSP (tem)
1242 && (SYMBOLP (XCAR (tem))
1243 || CONSP (XCAR (tem))))))
1244 error ("Invalid condition handler: %s",
1245 SDATA (Fprin1_to_string (tem, Qt)));
1248 /* The first clause is the one that should be checked first, so it
1249 should be added to handlerlist last. So build in CLAUSES a table
1250 that contains HANDLERS but in reverse order. CLAUSES is pointer
1251 to volatile to avoid issues with setjmp and local storage.
1252 SAFE_ALLOCA won't work here due to the setjmp, so impose a
1253 MAX_ALLOCA limit. */
1254 if (MAX_ALLOCA / word_size < clausenb)
1255 memory_full (SIZE_MAX);
1256 Lisp_Object volatile *clauses = alloca (clausenb * sizeof *clauses);
1257 clauses += clausenb;
1258 for (Lisp_Object tail = handlers; CONSP (tail); tail = XCDR (tail))
1259 *--clauses = XCAR (tail);
1260 for (ptrdiff_t i = 0; i < clausenb; i++)
1262 Lisp_Object clause = clauses[i];
1263 Lisp_Object condition = CONSP (clause) ? XCAR (clause) : Qnil;
1264 if (!CONSP (condition))
1265 condition = list1 (condition);
1266 struct handler *c = push_handler (condition, CONDITION_CASE);
1267 if (sys_setjmp (c->jmp))
1269 Lisp_Object val = handlerlist->val;
1270 Lisp_Object volatile *chosen_clause = clauses;
1271 for (struct handler *h = handlerlist->next; h != oldhandlerlist;
1272 h = h->next)
1273 chosen_clause++;
1274 Lisp_Object handler_body = XCDR (*chosen_clause);
1275 handlerlist = oldhandlerlist;
1277 if (NILP (var))
1278 return Fprogn (handler_body);
1280 Lisp_Object handler_var = var;
1281 if (!NILP (Vinternal_interpreter_environment))
1283 val = Fcons (Fcons (var, val),
1284 Vinternal_interpreter_environment);
1285 handler_var = Qinternal_interpreter_environment;
1288 /* Bind HANDLER_VAR to VAL while evaluating HANDLER_BODY.
1289 The unbind_to undoes just this binding; whoever longjumped
1290 to us unwound the stack to C->pdlcount before throwing. */
1291 ptrdiff_t count = SPECPDL_INDEX ();
1292 specbind (handler_var, val);
1293 return unbind_to (count, Fprogn (handler_body));
1297 Lisp_Object result = eval_sub (bodyform);
1298 handlerlist = oldhandlerlist;
1299 return result;
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 static 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 /* Check quit-flag and quit if it is non-nil. Typing C-g does not
1467 directly cause a quit; it only sets Vquit_flag. So the program
1468 needs to call maybe_quit at times when it is safe to quit. Every
1469 loop that might run for a long time or might not exit ought to call
1470 maybe_quit at least once, at a safe place. Unless that is
1471 impossible, of course. But it is very desirable to avoid creating
1472 loops where maybe_quit is impossible.
1474 If quit-flag is set to `kill-emacs' the SIGINT handler has received
1475 a request to exit Emacs when it is safe to do.
1477 When not quitting, process any pending signals. */
1479 void
1480 maybe_quit (void)
1482 if (!NILP (Vquit_flag) && NILP (Vinhibit_quit))
1483 process_quit_flag ();
1484 else if (pending_signals)
1485 process_pending_signals ();
1488 DEFUN ("signal", Fsignal, Ssignal, 2, 2, 0,
1489 doc: /* Signal an error. Args are ERROR-SYMBOL and associated DATA.
1490 This function does not return.
1492 An error symbol is a symbol with an `error-conditions' property
1493 that is a list of condition names.
1494 A handler for any of those names will get to handle this signal.
1495 The symbol `error' should normally be one of them.
1497 DATA should be a list. Its elements are printed as part of the error message.
1498 See Info anchor `(elisp)Definition of signal' for some details on how this
1499 error message is constructed.
1500 If the signal is handled, DATA is made available to the handler.
1501 See also the function `condition-case'. */
1502 attributes: noreturn)
1503 (Lisp_Object error_symbol, Lisp_Object data)
1505 signal_or_quit (error_symbol, data, false);
1506 eassume (false);
1509 /* Quit, in response to a keyboard quit request. */
1510 Lisp_Object
1511 quit (void)
1513 return signal_or_quit (Qquit, Qnil, true);
1516 /* Signal an error, or quit. ERROR_SYMBOL and DATA are as with Fsignal.
1517 If KEYBOARD_QUIT, this is a quit; ERROR_SYMBOL should be
1518 Qquit and DATA should be Qnil, and this function may return.
1519 Otherwise this function is like Fsignal and does not return. */
1521 static Lisp_Object
1522 signal_or_quit (Lisp_Object error_symbol, Lisp_Object data, bool keyboard_quit)
1524 /* When memory is full, ERROR-SYMBOL is nil,
1525 and DATA is (REAL-ERROR-SYMBOL . REAL-DATA).
1526 That is a special case--don't do this in other situations. */
1527 Lisp_Object conditions;
1528 Lisp_Object string;
1529 Lisp_Object real_error_symbol
1530 = (NILP (error_symbol) ? Fcar (data) : error_symbol);
1531 Lisp_Object clause = Qnil;
1532 struct handler *h;
1534 if (gc_in_progress || waiting_for_input)
1535 emacs_abort ();
1537 #if 0 /* rms: I don't know why this was here,
1538 but it is surely wrong for an error that is handled. */
1539 #ifdef HAVE_WINDOW_SYSTEM
1540 if (display_hourglass_p)
1541 cancel_hourglass ();
1542 #endif
1543 #endif
1545 /* This hook is used by edebug. */
1546 if (! NILP (Vsignal_hook_function)
1547 && ! NILP (error_symbol))
1549 /* Edebug takes care of restoring these variables when it exits. */
1550 if (lisp_eval_depth + 20 > max_lisp_eval_depth)
1551 max_lisp_eval_depth = lisp_eval_depth + 20;
1553 if (SPECPDL_INDEX () + 40 > max_specpdl_size)
1554 max_specpdl_size = SPECPDL_INDEX () + 40;
1556 call2 (Vsignal_hook_function, error_symbol, data);
1559 conditions = Fget (real_error_symbol, Qerror_conditions);
1561 /* Remember from where signal was called. Skip over the frame for
1562 `signal' itself. If a frame for `error' follows, skip that,
1563 too. Don't do this when ERROR_SYMBOL is nil, because that
1564 is a memory-full error. */
1565 Vsignaling_function = Qnil;
1566 if (!NILP (error_symbol))
1568 union specbinding *pdl = backtrace_next (backtrace_top ());
1569 if (backtrace_p (pdl) && EQ (backtrace_function (pdl), Qerror))
1570 pdl = backtrace_next (pdl);
1571 if (backtrace_p (pdl))
1572 Vsignaling_function = backtrace_function (pdl);
1575 for (h = handlerlist; h; h = h->next)
1577 if (h->type != CONDITION_CASE)
1578 continue;
1579 clause = find_handler_clause (h->tag_or_ch, conditions);
1580 if (!NILP (clause))
1581 break;
1584 if (/* Don't run the debugger for a memory-full error.
1585 (There is no room in memory to do that!) */
1586 !NILP (error_symbol)
1587 && (!NILP (Vdebug_on_signal)
1588 /* If no handler is present now, try to run the debugger. */
1589 || NILP (clause)
1590 /* A `debug' symbol in the handler list disables the normal
1591 suppression of the debugger. */
1592 || (CONSP (clause) && !NILP (Fmemq (Qdebug, clause)))
1593 /* Special handler that means "print a message and run debugger
1594 if requested". */
1595 || EQ (h->tag_or_ch, Qerror)))
1597 bool debugger_called
1598 = maybe_call_debugger (conditions, error_symbol, data);
1599 /* We can't return values to code which signaled an error, but we
1600 can continue code which has signaled a quit. */
1601 if (keyboard_quit && debugger_called && EQ (real_error_symbol, Qquit))
1602 return Qnil;
1605 if (!NILP (clause))
1607 Lisp_Object unwind_data
1608 = (NILP (error_symbol) ? data : Fcons (error_symbol, data));
1610 unwind_to_catch (h, unwind_data);
1612 else
1614 if (handlerlist != handlerlist_sentinel)
1615 /* FIXME: This will come right back here if there's no `top-level'
1616 catcher. A better solution would be to abort here, and instead
1617 add a catch-all condition handler so we never come here. */
1618 Fthrow (Qtop_level, Qt);
1621 if (! NILP (error_symbol))
1622 data = Fcons (error_symbol, data);
1624 string = Ferror_message_string (data);
1625 fatal ("%s", SDATA (string));
1628 /* Like xsignal, but takes 0, 1, 2, or 3 args instead of a list. */
1630 void
1631 xsignal0 (Lisp_Object error_symbol)
1633 xsignal (error_symbol, Qnil);
1636 void
1637 xsignal1 (Lisp_Object error_symbol, Lisp_Object arg)
1639 xsignal (error_symbol, list1 (arg));
1642 void
1643 xsignal2 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2)
1645 xsignal (error_symbol, list2 (arg1, arg2));
1648 void
1649 xsignal3 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
1651 xsignal (error_symbol, list3 (arg1, arg2, arg3));
1654 /* Signal `error' with message S, and additional arg ARG.
1655 If ARG is not a genuine list, make it a one-element list. */
1657 void
1658 signal_error (const char *s, Lisp_Object arg)
1660 Lisp_Object tortoise, hare;
1662 hare = tortoise = arg;
1663 while (CONSP (hare))
1665 hare = XCDR (hare);
1666 if (!CONSP (hare))
1667 break;
1669 hare = XCDR (hare);
1670 tortoise = XCDR (tortoise);
1672 if (EQ (hare, tortoise))
1673 break;
1676 if (!NILP (hare))
1677 arg = list1 (arg);
1679 xsignal (Qerror, Fcons (build_string (s), arg));
1683 /* Return true if LIST is a non-nil atom or
1684 a list containing one of CONDITIONS. */
1686 static bool
1687 wants_debugger (Lisp_Object list, Lisp_Object conditions)
1689 if (NILP (list))
1690 return 0;
1691 if (! CONSP (list))
1692 return 1;
1694 while (CONSP (conditions))
1696 Lisp_Object this, tail;
1697 this = XCAR (conditions);
1698 for (tail = list; CONSP (tail); tail = XCDR (tail))
1699 if (EQ (XCAR (tail), this))
1700 return 1;
1701 conditions = XCDR (conditions);
1703 return 0;
1706 /* Return true if an error with condition-symbols CONDITIONS,
1707 and described by SIGNAL-DATA, should skip the debugger
1708 according to debugger-ignored-errors. */
1710 static bool
1711 skip_debugger (Lisp_Object conditions, Lisp_Object data)
1713 Lisp_Object tail;
1714 bool first_string = 1;
1715 Lisp_Object error_message;
1717 error_message = Qnil;
1718 for (tail = Vdebug_ignored_errors; CONSP (tail); tail = XCDR (tail))
1720 if (STRINGP (XCAR (tail)))
1722 if (first_string)
1724 error_message = Ferror_message_string (data);
1725 first_string = 0;
1728 if (fast_string_match (XCAR (tail), error_message) >= 0)
1729 return 1;
1731 else
1733 Lisp_Object contail;
1735 for (contail = conditions; CONSP (contail); contail = XCDR (contail))
1736 if (EQ (XCAR (tail), XCAR (contail)))
1737 return 1;
1741 return 0;
1744 /* Call the debugger if calling it is currently enabled for CONDITIONS.
1745 SIG and DATA describe the signal. There are two ways to pass them:
1746 = SIG is the error symbol, and DATA is the rest of the data.
1747 = SIG is nil, and DATA is (SYMBOL . REST-OF-DATA).
1748 This is for memory-full errors only. */
1749 static bool
1750 maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig, Lisp_Object data)
1752 Lisp_Object combined_data;
1754 combined_data = Fcons (sig, data);
1756 if (
1757 /* Don't try to run the debugger with interrupts blocked.
1758 The editing loop would return anyway. */
1759 ! input_blocked_p ()
1760 && NILP (Vinhibit_debugger)
1761 /* Does user want to enter debugger for this kind of error? */
1762 && (EQ (sig, Qquit)
1763 ? debug_on_quit
1764 : wants_debugger (Vdebug_on_error, conditions))
1765 && ! skip_debugger (conditions, combined_data)
1766 /* RMS: What's this for? */
1767 && when_entered_debugger < num_nonmacro_input_events)
1769 call_debugger (list2 (Qerror, combined_data));
1770 return 1;
1773 return 0;
1776 static Lisp_Object
1777 find_handler_clause (Lisp_Object handlers, Lisp_Object conditions)
1779 register Lisp_Object h;
1781 /* t is used by handlers for all conditions, set up by C code. */
1782 if (EQ (handlers, Qt))
1783 return Qt;
1785 /* error is used similarly, but means print an error message
1786 and run the debugger if that is enabled. */
1787 if (EQ (handlers, Qerror))
1788 return Qt;
1790 for (h = handlers; CONSP (h); h = XCDR (h))
1792 Lisp_Object handler = XCAR (h);
1793 if (!NILP (Fmemq (handler, conditions)))
1794 return handlers;
1797 return Qnil;
1801 /* Format and return a string; called like vprintf. */
1802 Lisp_Object
1803 vformat_string (const char *m, va_list ap)
1805 char buf[4000];
1806 ptrdiff_t size = sizeof buf;
1807 ptrdiff_t size_max = STRING_BYTES_BOUND + 1;
1808 char *buffer = buf;
1809 ptrdiff_t used;
1810 Lisp_Object string;
1812 used = evxprintf (&buffer, &size, buf, size_max, m, ap);
1813 string = make_string (buffer, used);
1814 if (buffer != buf)
1815 xfree (buffer);
1817 return string;
1820 /* Dump an error message; called like vprintf. */
1821 void
1822 verror (const char *m, va_list ap)
1824 xsignal1 (Qerror, vformat_string (m, ap));
1828 /* Dump an error message; called like printf. */
1830 /* VARARGS 1 */
1831 void
1832 error (const char *m, ...)
1834 va_list ap;
1835 va_start (ap, m);
1836 verror (m, ap);
1839 DEFUN ("commandp", Fcommandp, Scommandp, 1, 2, 0,
1840 doc: /* Non-nil if FUNCTION makes provisions for interactive calling.
1841 This means it contains a description for how to read arguments to give it.
1842 The value is nil for an invalid function or a symbol with no function
1843 definition.
1845 Interactively callable functions include strings and vectors (treated
1846 as keyboard macros), lambda-expressions that contain a top-level call
1847 to `interactive', autoload definitions made by `autoload' with non-nil
1848 fourth argument, and some of the built-in functions of Lisp.
1850 Also, a symbol satisfies `commandp' if its function definition does so.
1852 If the optional argument FOR-CALL-INTERACTIVELY is non-nil,
1853 then strings and vectors are not accepted. */)
1854 (Lisp_Object function, Lisp_Object for_call_interactively)
1856 register Lisp_Object fun;
1857 register Lisp_Object funcar;
1858 Lisp_Object if_prop = Qnil;
1860 fun = function;
1862 fun = indirect_function (fun); /* Check cycles. */
1863 if (NILP (fun))
1864 return Qnil;
1866 /* Check an `interactive-form' property if present, analogous to the
1867 function-documentation property. */
1868 fun = function;
1869 while (SYMBOLP (fun))
1871 Lisp_Object tmp = Fget (fun, Qinteractive_form);
1872 if (!NILP (tmp))
1873 if_prop = Qt;
1874 fun = Fsymbol_function (fun);
1877 /* Emacs primitives are interactive if their DEFUN specifies an
1878 interactive spec. */
1879 if (SUBRP (fun))
1880 return XSUBR (fun)->intspec ? Qt : if_prop;
1882 /* Bytecode objects are interactive if they are long enough to
1883 have an element whose index is COMPILED_INTERACTIVE, which is
1884 where the interactive spec is stored. */
1885 else if (COMPILEDP (fun))
1886 return (PVSIZE (fun) > COMPILED_INTERACTIVE ? Qt : if_prop);
1888 /* Strings and vectors are keyboard macros. */
1889 if (STRINGP (fun) || VECTORP (fun))
1890 return (NILP (for_call_interactively) ? Qt : Qnil);
1892 /* Lists may represent commands. */
1893 if (!CONSP (fun))
1894 return Qnil;
1895 funcar = XCAR (fun);
1896 if (EQ (funcar, Qclosure))
1897 return (!NILP (Fassq (Qinteractive, Fcdr (Fcdr (XCDR (fun)))))
1898 ? Qt : if_prop);
1899 else if (EQ (funcar, Qlambda))
1900 return !NILP (Fassq (Qinteractive, Fcdr (XCDR (fun)))) ? Qt : if_prop;
1901 else if (EQ (funcar, Qautoload))
1902 return !NILP (Fcar (Fcdr (Fcdr (XCDR (fun))))) ? Qt : if_prop;
1903 else
1904 return Qnil;
1907 DEFUN ("autoload", Fautoload, Sautoload, 2, 5, 0,
1908 doc: /* Define FUNCTION to autoload from FILE.
1909 FUNCTION is a symbol; FILE is a file name string to pass to `load'.
1910 Third arg DOCSTRING is documentation for the function.
1911 Fourth arg INTERACTIVE if non-nil says function can be called interactively.
1912 Fifth arg TYPE indicates the type of the object:
1913 nil or omitted says FUNCTION is a function,
1914 `keymap' says FUNCTION is really a keymap, and
1915 `macro' or t says FUNCTION is really a macro.
1916 Third through fifth args give info about the real definition.
1917 They default to nil.
1918 If FUNCTION is already defined other than as an autoload,
1919 this does nothing and returns nil. */)
1920 (Lisp_Object function, Lisp_Object file, Lisp_Object docstring, Lisp_Object interactive, Lisp_Object type)
1922 CHECK_SYMBOL (function);
1923 CHECK_STRING (file);
1925 /* If function is defined and not as an autoload, don't override. */
1926 if (!NILP (XSYMBOL (function)->function)
1927 && !AUTOLOADP (XSYMBOL (function)->function))
1928 return Qnil;
1930 if (!NILP (Vpurify_flag) && EQ (docstring, make_number (0)))
1931 /* `read1' in lread.c has found the docstring starting with "\
1932 and assumed the docstring will be provided by Snarf-documentation, so it
1933 passed us 0 instead. But that leads to accidental sharing in purecopy's
1934 hash-consing, so we use a (hopefully) unique integer instead. */
1935 docstring = make_number (XHASH (function));
1936 return Fdefalias (function,
1937 list5 (Qautoload, file, docstring, interactive, type),
1938 Qnil);
1941 void
1942 un_autoload (Lisp_Object oldqueue)
1944 Lisp_Object queue, first, second;
1946 /* Queue to unwind is current value of Vautoload_queue.
1947 oldqueue is the shadowed value to leave in Vautoload_queue. */
1948 queue = Vautoload_queue;
1949 Vautoload_queue = oldqueue;
1950 while (CONSP (queue))
1952 first = XCAR (queue);
1953 second = Fcdr (first);
1954 first = Fcar (first);
1955 if (EQ (first, make_number (0)))
1956 Vfeatures = second;
1957 else
1958 Ffset (first, second);
1959 queue = XCDR (queue);
1963 /* Load an autoloaded function.
1964 FUNNAME is the symbol which is the function's name.
1965 FUNDEF is the autoload definition (a list). */
1967 DEFUN ("autoload-do-load", Fautoload_do_load, Sautoload_do_load, 1, 3, 0,
1968 doc: /* Load FUNDEF which should be an autoload.
1969 If non-nil, FUNNAME should be the symbol whose function value is FUNDEF,
1970 in which case the function returns the new autoloaded function value.
1971 If equal to `macro', MACRO-ONLY specifies that FUNDEF should only be loaded if
1972 it defines a macro. */)
1973 (Lisp_Object fundef, Lisp_Object funname, Lisp_Object macro_only)
1975 ptrdiff_t count = SPECPDL_INDEX ();
1977 if (!CONSP (fundef) || !EQ (Qautoload, XCAR (fundef)))
1978 return fundef;
1980 if (EQ (macro_only, Qmacro))
1982 Lisp_Object kind = Fnth (make_number (4), fundef);
1983 if (! (EQ (kind, Qt) || EQ (kind, Qmacro)))
1984 return fundef;
1987 /* This is to make sure that loadup.el gives a clear picture
1988 of what files are preloaded and when. */
1989 if (! NILP (Vpurify_flag))
1990 error ("Attempt to autoload %s while preparing to dump",
1991 SDATA (SYMBOL_NAME (funname)));
1993 CHECK_SYMBOL (funname);
1995 /* Preserve the match data. */
1996 record_unwind_save_match_data ();
1998 /* If autoloading gets an error (which includes the error of failing
1999 to define the function being called), we use Vautoload_queue
2000 to undo function definitions and `provide' calls made by
2001 the function. We do this in the specific case of autoloading
2002 because autoloading is not an explicit request "load this file",
2003 but rather a request to "call this function".
2005 The value saved here is to be restored into Vautoload_queue. */
2006 record_unwind_protect (un_autoload, Vautoload_queue);
2007 Vautoload_queue = Qt;
2008 /* If `macro_only', assume this autoload to be a "best-effort",
2009 so don't signal an error if autoloading fails. */
2010 Fload (Fcar (Fcdr (fundef)), macro_only, Qt, Qnil, Qt);
2012 /* Once loading finishes, don't undo it. */
2013 Vautoload_queue = Qt;
2014 unbind_to (count, Qnil);
2016 if (NILP (funname))
2017 return Qnil;
2018 else
2020 Lisp_Object fun = Findirect_function (funname, Qnil);
2022 if (!NILP (Fequal (fun, fundef)))
2023 error ("Autoloading file %s failed to define function %s",
2024 SDATA (Fcar (Fcar (Vload_history))),
2025 SDATA (SYMBOL_NAME (funname)));
2026 else
2027 return fun;
2032 DEFUN ("eval", Feval, Seval, 1, 2, 0,
2033 doc: /* Evaluate FORM and return its value.
2034 If LEXICAL is t, evaluate using lexical scoping.
2035 LEXICAL can also be an actual lexical environment, in the form of an
2036 alist mapping symbols to their value. */)
2037 (Lisp_Object form, Lisp_Object lexical)
2039 ptrdiff_t count = SPECPDL_INDEX ();
2040 specbind (Qinternal_interpreter_environment,
2041 CONSP (lexical) || NILP (lexical) ? lexical : list1 (Qt));
2042 return unbind_to (count, eval_sub (form));
2045 /* Grow the specpdl stack by one entry.
2046 The caller should have already initialized the entry.
2047 Signal an error on stack overflow.
2049 Make sure that there is always one unused entry past the top of the
2050 stack, so that the just-initialized entry is safely unwound if
2051 memory exhausted and an error is signaled here. Also, allocate a
2052 never-used entry just before the bottom of the stack; sometimes its
2053 address is taken. */
2055 static void
2056 grow_specpdl (void)
2058 specpdl_ptr++;
2060 if (specpdl_ptr == specpdl + specpdl_size)
2062 ptrdiff_t count = SPECPDL_INDEX ();
2063 ptrdiff_t max_size = min (max_specpdl_size, PTRDIFF_MAX - 1000);
2064 union specbinding *pdlvec = specpdl - 1;
2065 ptrdiff_t pdlvecsize = specpdl_size + 1;
2066 if (max_size <= specpdl_size)
2068 if (max_specpdl_size < 400)
2069 max_size = max_specpdl_size = 400;
2070 if (max_size <= specpdl_size)
2071 signal_error ("Variable binding depth exceeds max-specpdl-size",
2072 Qnil);
2074 pdlvec = xpalloc (pdlvec, &pdlvecsize, 1, max_size + 1, sizeof *specpdl);
2075 specpdl = pdlvec + 1;
2076 specpdl_size = pdlvecsize - 1;
2077 specpdl_ptr = specpdl + count;
2081 ptrdiff_t
2082 record_in_backtrace (Lisp_Object function, Lisp_Object *args, ptrdiff_t nargs)
2084 ptrdiff_t count = SPECPDL_INDEX ();
2086 eassert (nargs >= UNEVALLED);
2087 specpdl_ptr->bt.kind = SPECPDL_BACKTRACE;
2088 specpdl_ptr->bt.debug_on_exit = false;
2089 specpdl_ptr->bt.function = function;
2090 specpdl_ptr->bt.args = args;
2091 specpdl_ptr->bt.nargs = nargs;
2092 grow_specpdl ();
2094 return count;
2097 /* Eval a sub-expression of the current expression (i.e. in the same
2098 lexical scope). */
2099 Lisp_Object
2100 eval_sub (Lisp_Object form)
2102 Lisp_Object fun, val, original_fun, original_args;
2103 Lisp_Object funcar;
2104 ptrdiff_t count;
2106 /* Declare here, as this array may be accessed by call_debugger near
2107 the end of this function. See Bug#21245. */
2108 Lisp_Object argvals[8];
2110 if (SYMBOLP (form))
2112 /* Look up its binding in the lexical environment.
2113 We do not pay attention to the declared_special flag here, since we
2114 already did that when let-binding the variable. */
2115 Lisp_Object lex_binding
2116 = !NILP (Vinternal_interpreter_environment) /* Mere optimization! */
2117 ? Fassq (form, Vinternal_interpreter_environment)
2118 : Qnil;
2119 if (CONSP (lex_binding))
2120 return XCDR (lex_binding);
2121 else
2122 return Fsymbol_value (form);
2125 if (!CONSP (form))
2126 return form;
2128 maybe_quit ();
2130 maybe_gc ();
2132 if (++lisp_eval_depth > max_lisp_eval_depth)
2134 if (max_lisp_eval_depth < 100)
2135 max_lisp_eval_depth = 100;
2136 if (lisp_eval_depth > max_lisp_eval_depth)
2137 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2140 original_fun = XCAR (form);
2141 original_args = XCDR (form);
2143 /* This also protects them from gc. */
2144 count = record_in_backtrace (original_fun, &original_args, UNEVALLED);
2146 if (debug_on_next_call)
2147 do_debug_on_call (Qt, count);
2149 /* At this point, only original_fun and original_args
2150 have values that will be used below. */
2151 retry:
2153 /* Optimize for no indirection. */
2154 fun = original_fun;
2155 if (!SYMBOLP (fun))
2156 fun = Ffunction (Fcons (fun, Qnil));
2157 else if (!NILP (fun) && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2158 fun = indirect_function (fun);
2160 if (SUBRP (fun))
2162 Lisp_Object args_left = original_args;
2163 Lisp_Object numargs = Flength (args_left);
2165 check_cons_list ();
2167 if (XINT (numargs) < XSUBR (fun)->min_args
2168 || (XSUBR (fun)->max_args >= 0
2169 && XSUBR (fun)->max_args < XINT (numargs)))
2170 xsignal2 (Qwrong_number_of_arguments, original_fun, numargs);
2172 else if (XSUBR (fun)->max_args == UNEVALLED)
2173 val = (XSUBR (fun)->function.aUNEVALLED) (args_left);
2174 else if (XSUBR (fun)->max_args == MANY)
2176 /* Pass a vector of evaluated arguments. */
2177 Lisp_Object *vals;
2178 ptrdiff_t argnum = 0;
2179 USE_SAFE_ALLOCA;
2181 SAFE_ALLOCA_LISP (vals, XINT (numargs));
2183 while (!NILP (args_left))
2185 vals[argnum++] = eval_sub (Fcar (args_left));
2186 args_left = Fcdr (args_left);
2189 set_backtrace_args (specpdl + count, vals, XINT (numargs));
2191 val = (XSUBR (fun)->function.aMANY) (XINT (numargs), vals);
2193 check_cons_list ();
2194 lisp_eval_depth--;
2195 /* Do the debug-on-exit now, while VALS still exists. */
2196 if (backtrace_debug_on_exit (specpdl + count))
2197 val = call_debugger (list2 (Qexit, val));
2198 SAFE_FREE ();
2199 specpdl_ptr--;
2200 return val;
2202 else
2204 int i, maxargs = XSUBR (fun)->max_args;
2206 for (i = 0; i < maxargs; i++)
2208 argvals[i] = eval_sub (Fcar (args_left));
2209 args_left = Fcdr (args_left);
2212 set_backtrace_args (specpdl + count, argvals, XINT (numargs));
2214 switch (i)
2216 case 0:
2217 val = (XSUBR (fun)->function.a0 ());
2218 break;
2219 case 1:
2220 val = (XSUBR (fun)->function.a1 (argvals[0]));
2221 break;
2222 case 2:
2223 val = (XSUBR (fun)->function.a2 (argvals[0], argvals[1]));
2224 break;
2225 case 3:
2226 val = (XSUBR (fun)->function.a3
2227 (argvals[0], argvals[1], argvals[2]));
2228 break;
2229 case 4:
2230 val = (XSUBR (fun)->function.a4
2231 (argvals[0], argvals[1], argvals[2], argvals[3]));
2232 break;
2233 case 5:
2234 val = (XSUBR (fun)->function.a5
2235 (argvals[0], argvals[1], argvals[2], argvals[3],
2236 argvals[4]));
2237 break;
2238 case 6:
2239 val = (XSUBR (fun)->function.a6
2240 (argvals[0], argvals[1], argvals[2], argvals[3],
2241 argvals[4], argvals[5]));
2242 break;
2243 case 7:
2244 val = (XSUBR (fun)->function.a7
2245 (argvals[0], argvals[1], argvals[2], argvals[3],
2246 argvals[4], argvals[5], argvals[6]));
2247 break;
2249 case 8:
2250 val = (XSUBR (fun)->function.a8
2251 (argvals[0], argvals[1], argvals[2], argvals[3],
2252 argvals[4], argvals[5], argvals[6], argvals[7]));
2253 break;
2255 default:
2256 /* Someone has created a subr that takes more arguments than
2257 is supported by this code. We need to either rewrite the
2258 subr to use a different argument protocol, or add more
2259 cases to this switch. */
2260 emacs_abort ();
2264 else if (COMPILEDP (fun) || MODULE_FUNCTIONP (fun))
2265 return apply_lambda (fun, original_args, count);
2266 else
2268 if (NILP (fun))
2269 xsignal1 (Qvoid_function, original_fun);
2270 if (!CONSP (fun))
2271 xsignal1 (Qinvalid_function, original_fun);
2272 funcar = XCAR (fun);
2273 if (!SYMBOLP (funcar))
2274 xsignal1 (Qinvalid_function, original_fun);
2275 if (EQ (funcar, Qautoload))
2277 Fautoload_do_load (fun, original_fun, Qnil);
2278 goto retry;
2280 if (EQ (funcar, Qmacro))
2282 ptrdiff_t count1 = SPECPDL_INDEX ();
2283 Lisp_Object exp;
2284 /* Bind lexical-binding during expansion of the macro, so the
2285 macro can know reliably if the code it outputs will be
2286 interpreted using lexical-binding or not. */
2287 specbind (Qlexical_binding,
2288 NILP (Vinternal_interpreter_environment) ? Qnil : Qt);
2289 exp = apply1 (Fcdr (fun), original_args);
2290 unbind_to (count1, Qnil);
2291 val = eval_sub (exp);
2293 else if (EQ (funcar, Qlambda)
2294 || EQ (funcar, Qclosure))
2295 return apply_lambda (fun, original_args, count);
2296 else
2297 xsignal1 (Qinvalid_function, original_fun);
2299 check_cons_list ();
2301 lisp_eval_depth--;
2302 if (backtrace_debug_on_exit (specpdl + count))
2303 val = call_debugger (list2 (Qexit, val));
2304 specpdl_ptr--;
2306 return val;
2309 DEFUN ("apply", Fapply, Sapply, 1, MANY, 0,
2310 doc: /* Call FUNCTION with our remaining args, using our last arg as list of args.
2311 Then return the value FUNCTION returns.
2312 Thus, (apply \\='+ 1 2 \\='(3 4)) returns 10.
2313 usage: (apply FUNCTION &rest ARGUMENTS) */)
2314 (ptrdiff_t nargs, Lisp_Object *args)
2316 ptrdiff_t i, numargs, funcall_nargs;
2317 register Lisp_Object *funcall_args = NULL;
2318 register Lisp_Object spread_arg = args[nargs - 1];
2319 Lisp_Object fun = args[0];
2320 Lisp_Object retval;
2321 USE_SAFE_ALLOCA;
2323 CHECK_LIST (spread_arg);
2325 numargs = XINT (Flength (spread_arg));
2327 if (numargs == 0)
2328 return Ffuncall (nargs - 1, args);
2329 else if (numargs == 1)
2331 args [nargs - 1] = XCAR (spread_arg);
2332 return Ffuncall (nargs, args);
2335 numargs += nargs - 2;
2337 /* Optimize for no indirection. */
2338 if (SYMBOLP (fun) && !NILP (fun)
2339 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2341 fun = indirect_function (fun);
2342 if (NILP (fun))
2343 /* Let funcall get the error. */
2344 fun = args[0];
2347 if (SUBRP (fun) && XSUBR (fun)->max_args > numargs
2348 /* Don't hide an error by adding missing arguments. */
2349 && numargs >= XSUBR (fun)->min_args)
2351 /* Avoid making funcall cons up a yet another new vector of arguments
2352 by explicitly supplying nil's for optional values. */
2353 SAFE_ALLOCA_LISP (funcall_args, 1 + XSUBR (fun)->max_args);
2354 memclear (funcall_args + numargs + 1,
2355 (XSUBR (fun)->max_args - numargs) * word_size);
2356 funcall_nargs = 1 + XSUBR (fun)->max_args;
2358 else
2359 { /* We add 1 to numargs because funcall_args includes the
2360 function itself as well as its arguments. */
2361 SAFE_ALLOCA_LISP (funcall_args, 1 + numargs);
2362 funcall_nargs = 1 + numargs;
2365 memcpy (funcall_args, args, nargs * word_size);
2366 /* Spread the last arg we got. Its first element goes in
2367 the slot that it used to occupy, hence this value of I. */
2368 i = nargs - 1;
2369 while (!NILP (spread_arg))
2371 funcall_args [i++] = XCAR (spread_arg);
2372 spread_arg = XCDR (spread_arg);
2375 retval = Ffuncall (funcall_nargs, funcall_args);
2377 SAFE_FREE ();
2378 return retval;
2381 /* Run hook variables in various ways. */
2383 static Lisp_Object
2384 funcall_nil (ptrdiff_t nargs, Lisp_Object *args)
2386 Ffuncall (nargs, args);
2387 return Qnil;
2390 DEFUN ("run-hooks", Frun_hooks, Srun_hooks, 0, MANY, 0,
2391 doc: /* Run each hook in HOOKS.
2392 Each argument should be a symbol, a hook variable.
2393 These symbols are processed in the order specified.
2394 If a hook symbol has a non-nil value, that value may be a function
2395 or a list of functions to be called to run the hook.
2396 If the value is a function, it is called with no arguments.
2397 If it is a list, the elements are called, in order, with no arguments.
2399 Major modes should not use this function directly to run their mode
2400 hook; they should use `run-mode-hooks' instead.
2402 Do not use `make-local-variable' to make a hook variable buffer-local.
2403 Instead, use `add-hook' and specify t for the LOCAL argument.
2404 usage: (run-hooks &rest HOOKS) */)
2405 (ptrdiff_t nargs, Lisp_Object *args)
2407 ptrdiff_t i;
2409 for (i = 0; i < nargs; i++)
2410 run_hook (args[i]);
2412 return Qnil;
2415 DEFUN ("run-hook-with-args", Frun_hook_with_args,
2416 Srun_hook_with_args, 1, MANY, 0,
2417 doc: /* Run HOOK with the specified arguments ARGS.
2418 HOOK should be a symbol, a hook variable. The value of HOOK
2419 may be nil, a function, or a list of functions. Call each
2420 function in order with arguments ARGS. The final return value
2421 is unspecified.
2423 Do not use `make-local-variable' to make a hook variable buffer-local.
2424 Instead, use `add-hook' and specify t for the LOCAL argument.
2425 usage: (run-hook-with-args HOOK &rest ARGS) */)
2426 (ptrdiff_t nargs, Lisp_Object *args)
2428 return run_hook_with_args (nargs, args, funcall_nil);
2431 /* NB this one still documents a specific non-nil return value.
2432 (As did run-hook-with-args and run-hook-with-args-until-failure
2433 until they were changed in 24.1.) */
2434 DEFUN ("run-hook-with-args-until-success", Frun_hook_with_args_until_success,
2435 Srun_hook_with_args_until_success, 1, MANY, 0,
2436 doc: /* Run HOOK with the specified arguments ARGS.
2437 HOOK should be a symbol, a hook variable. The value of HOOK
2438 may be nil, a function, or a list of functions. Call each
2439 function in order with arguments ARGS, stopping at the first
2440 one that returns non-nil, and return that value. Otherwise (if
2441 all functions return nil, or if there are no functions to call),
2442 return nil.
2444 Do not use `make-local-variable' to make a hook variable buffer-local.
2445 Instead, use `add-hook' and specify t for the LOCAL argument.
2446 usage: (run-hook-with-args-until-success HOOK &rest ARGS) */)
2447 (ptrdiff_t nargs, Lisp_Object *args)
2449 return run_hook_with_args (nargs, args, Ffuncall);
2452 static Lisp_Object
2453 funcall_not (ptrdiff_t nargs, Lisp_Object *args)
2455 return NILP (Ffuncall (nargs, args)) ? Qt : Qnil;
2458 DEFUN ("run-hook-with-args-until-failure", Frun_hook_with_args_until_failure,
2459 Srun_hook_with_args_until_failure, 1, MANY, 0,
2460 doc: /* Run HOOK with the specified arguments ARGS.
2461 HOOK should be a symbol, a hook variable. The value of HOOK
2462 may be nil, a function, or a list of functions. Call each
2463 function in order with arguments ARGS, stopping at the first
2464 one that returns nil, and return nil. Otherwise (if all functions
2465 return non-nil, or if there are no functions to call), return non-nil
2466 \(do not rely on the precise return value in this case).
2468 Do not use `make-local-variable' to make a hook variable buffer-local.
2469 Instead, use `add-hook' and specify t for the LOCAL argument.
2470 usage: (run-hook-with-args-until-failure HOOK &rest ARGS) */)
2471 (ptrdiff_t nargs, Lisp_Object *args)
2473 return NILP (run_hook_with_args (nargs, args, funcall_not)) ? Qt : Qnil;
2476 static Lisp_Object
2477 run_hook_wrapped_funcall (ptrdiff_t nargs, Lisp_Object *args)
2479 Lisp_Object tmp = args[0], ret;
2480 args[0] = args[1];
2481 args[1] = tmp;
2482 ret = Ffuncall (nargs, args);
2483 args[1] = args[0];
2484 args[0] = tmp;
2485 return ret;
2488 DEFUN ("run-hook-wrapped", Frun_hook_wrapped, Srun_hook_wrapped, 2, MANY, 0,
2489 doc: /* Run HOOK, passing each function through WRAP-FUNCTION.
2490 I.e. instead of calling each function FUN directly with arguments ARGS,
2491 it calls WRAP-FUNCTION with arguments FUN and ARGS.
2492 As soon as a call to WRAP-FUNCTION returns non-nil, `run-hook-wrapped'
2493 aborts and returns that value.
2494 usage: (run-hook-wrapped HOOK WRAP-FUNCTION &rest ARGS) */)
2495 (ptrdiff_t nargs, Lisp_Object *args)
2497 return run_hook_with_args (nargs, args, run_hook_wrapped_funcall);
2500 /* ARGS[0] should be a hook symbol.
2501 Call each of the functions in the hook value, passing each of them
2502 as arguments all the rest of ARGS (all NARGS - 1 elements).
2503 FUNCALL specifies how to call each function on the hook. */
2505 Lisp_Object
2506 run_hook_with_args (ptrdiff_t nargs, Lisp_Object *args,
2507 Lisp_Object (*funcall) (ptrdiff_t nargs, Lisp_Object *args))
2509 Lisp_Object sym, val, ret = Qnil;
2511 /* If we are dying or still initializing,
2512 don't do anything--it would probably crash if we tried. */
2513 if (NILP (Vrun_hooks))
2514 return Qnil;
2516 sym = args[0];
2517 val = find_symbol_value (sym);
2519 if (EQ (val, Qunbound) || NILP (val))
2520 return ret;
2521 else if (!CONSP (val) || FUNCTIONP (val))
2523 args[0] = val;
2524 return funcall (nargs, args);
2526 else
2528 Lisp_Object global_vals = Qnil;
2530 for (;
2531 CONSP (val) && NILP (ret);
2532 val = XCDR (val))
2534 if (EQ (XCAR (val), Qt))
2536 /* t indicates this hook has a local binding;
2537 it means to run the global binding too. */
2538 global_vals = Fdefault_value (sym);
2539 if (NILP (global_vals)) continue;
2541 if (!CONSP (global_vals) || EQ (XCAR (global_vals), Qlambda))
2543 args[0] = global_vals;
2544 ret = funcall (nargs, args);
2546 else
2548 for (;
2549 CONSP (global_vals) && NILP (ret);
2550 global_vals = XCDR (global_vals))
2552 args[0] = XCAR (global_vals);
2553 /* In a global value, t should not occur. If it does, we
2554 must ignore it to avoid an endless loop. */
2555 if (!EQ (args[0], Qt))
2556 ret = funcall (nargs, args);
2560 else
2562 args[0] = XCAR (val);
2563 ret = funcall (nargs, args);
2567 return ret;
2571 /* Run the hook HOOK, giving each function no args. */
2573 void
2574 run_hook (Lisp_Object hook)
2576 Frun_hook_with_args (1, &hook);
2579 /* Run the hook HOOK, giving each function the two args ARG1 and ARG2. */
2581 void
2582 run_hook_with_args_2 (Lisp_Object hook, Lisp_Object arg1, Lisp_Object arg2)
2584 CALLN (Frun_hook_with_args, hook, arg1, arg2);
2587 /* Apply fn to arg. */
2588 Lisp_Object
2589 apply1 (Lisp_Object fn, Lisp_Object arg)
2591 return NILP (arg) ? Ffuncall (1, &fn) : CALLN (Fapply, fn, arg);
2594 /* Call function fn on no arguments. */
2595 Lisp_Object
2596 call0 (Lisp_Object fn)
2598 return Ffuncall (1, &fn);
2601 /* Call function fn with 1 argument arg1. */
2602 /* ARGSUSED */
2603 Lisp_Object
2604 call1 (Lisp_Object fn, Lisp_Object arg1)
2606 return CALLN (Ffuncall, fn, arg1);
2609 /* Call function fn with 2 arguments arg1, arg2. */
2610 /* ARGSUSED */
2611 Lisp_Object
2612 call2 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2)
2614 return CALLN (Ffuncall, fn, arg1, arg2);
2617 /* Call function fn with 3 arguments arg1, arg2, arg3. */
2618 /* ARGSUSED */
2619 Lisp_Object
2620 call3 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2622 return CALLN (Ffuncall, fn, arg1, arg2, arg3);
2625 /* Call function fn with 4 arguments arg1, arg2, arg3, arg4. */
2626 /* ARGSUSED */
2627 Lisp_Object
2628 call4 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2629 Lisp_Object arg4)
2631 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4);
2634 /* Call function fn with 5 arguments arg1, arg2, arg3, arg4, arg5. */
2635 /* ARGSUSED */
2636 Lisp_Object
2637 call5 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2638 Lisp_Object arg4, Lisp_Object arg5)
2640 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5);
2643 /* Call function fn with 6 arguments arg1, arg2, arg3, arg4, arg5, arg6. */
2644 /* ARGSUSED */
2645 Lisp_Object
2646 call6 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2647 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6)
2649 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6);
2652 /* Call function fn with 7 arguments arg1, arg2, arg3, arg4, arg5, arg6, arg7. */
2653 /* ARGSUSED */
2654 Lisp_Object
2655 call7 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2656 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6, Lisp_Object arg7)
2658 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
2661 DEFUN ("functionp", Ffunctionp, Sfunctionp, 1, 1, 0,
2662 doc: /* Non-nil if OBJECT is a function. */)
2663 (Lisp_Object object)
2665 if (FUNCTIONP (object))
2666 return Qt;
2667 return Qnil;
2670 bool
2671 FUNCTIONP (Lisp_Object object)
2673 if (SYMBOLP (object) && !NILP (Ffboundp (object)))
2675 object = Findirect_function (object, Qt);
2677 if (CONSP (object) && EQ (XCAR (object), Qautoload))
2679 /* Autoloaded symbols are functions, except if they load
2680 macros or keymaps. */
2681 for (int i = 0; i < 4 && CONSP (object); i++)
2682 object = XCDR (object);
2684 return ! (CONSP (object) && !NILP (XCAR (object)));
2688 if (SUBRP (object))
2689 return XSUBR (object)->max_args != UNEVALLED;
2690 else if (COMPILEDP (object) || MODULE_FUNCTIONP (object))
2691 return true;
2692 else if (CONSP (object))
2694 Lisp_Object car = XCAR (object);
2695 return EQ (car, Qlambda) || EQ (car, Qclosure);
2697 else
2698 return false;
2701 DEFUN ("funcall", Ffuncall, Sfuncall, 1, MANY, 0,
2702 doc: /* Call first argument as a function, passing remaining arguments to it.
2703 Return the value that function returns.
2704 Thus, (funcall \\='cons \\='x \\='y) returns (x . y).
2705 usage: (funcall FUNCTION &rest ARGUMENTS) */)
2706 (ptrdiff_t nargs, Lisp_Object *args)
2708 Lisp_Object fun, original_fun;
2709 Lisp_Object funcar;
2710 ptrdiff_t numargs = nargs - 1;
2711 Lisp_Object val;
2712 ptrdiff_t count;
2714 maybe_quit ();
2716 if (++lisp_eval_depth > max_lisp_eval_depth)
2718 if (max_lisp_eval_depth < 100)
2719 max_lisp_eval_depth = 100;
2720 if (lisp_eval_depth > max_lisp_eval_depth)
2721 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2724 count = record_in_backtrace (args[0], &args[1], nargs - 1);
2726 maybe_gc ();
2728 if (debug_on_next_call)
2729 do_debug_on_call (Qlambda, count);
2731 check_cons_list ();
2733 original_fun = args[0];
2735 retry:
2737 /* Optimize for no indirection. */
2738 fun = original_fun;
2739 if (SYMBOLP (fun) && !NILP (fun)
2740 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2741 fun = indirect_function (fun);
2743 if (SUBRP (fun))
2744 val = funcall_subr (XSUBR (fun), numargs, args + 1);
2745 else if (COMPILEDP (fun) || MODULE_FUNCTIONP (fun))
2746 val = funcall_lambda (fun, numargs, args + 1);
2747 else
2749 if (NILP (fun))
2750 xsignal1 (Qvoid_function, original_fun);
2751 if (!CONSP (fun))
2752 xsignal1 (Qinvalid_function, original_fun);
2753 funcar = XCAR (fun);
2754 if (!SYMBOLP (funcar))
2755 xsignal1 (Qinvalid_function, original_fun);
2756 if (EQ (funcar, Qlambda)
2757 || EQ (funcar, Qclosure))
2758 val = funcall_lambda (fun, numargs, args + 1);
2759 else if (EQ (funcar, Qautoload))
2761 Fautoload_do_load (fun, original_fun, Qnil);
2762 check_cons_list ();
2763 goto retry;
2765 else
2766 xsignal1 (Qinvalid_function, original_fun);
2768 check_cons_list ();
2769 lisp_eval_depth--;
2770 if (backtrace_debug_on_exit (specpdl + count))
2771 val = call_debugger (list2 (Qexit, val));
2772 specpdl_ptr--;
2773 return val;
2777 /* Apply a C subroutine SUBR to the NUMARGS evaluated arguments in ARG_VECTOR
2778 and return the result of evaluation. */
2780 Lisp_Object
2781 funcall_subr (struct Lisp_Subr *subr, ptrdiff_t numargs, Lisp_Object *args)
2783 if (numargs < subr->min_args
2784 || (subr->max_args >= 0 && subr->max_args < numargs))
2786 Lisp_Object fun;
2787 XSETSUBR (fun, subr);
2788 xsignal2 (Qwrong_number_of_arguments, fun, make_number (numargs));
2791 else if (subr->max_args == UNEVALLED)
2793 Lisp_Object fun;
2794 XSETSUBR (fun, subr);
2795 xsignal1 (Qinvalid_function, fun);
2798 else if (subr->max_args == MANY)
2799 return (subr->function.aMANY) (numargs, args);
2800 else
2802 Lisp_Object internal_argbuf[8];
2803 Lisp_Object *internal_args;
2804 if (subr->max_args > numargs)
2806 eassert (subr->max_args <= ARRAYELTS (internal_argbuf));
2807 internal_args = internal_argbuf;
2808 memcpy (internal_args, args, numargs * word_size);
2809 memclear (internal_args + numargs,
2810 (subr->max_args - numargs) * word_size);
2812 else
2813 internal_args = args;
2814 switch (subr->max_args)
2816 case 0:
2817 return (subr->function.a0 ());
2818 case 1:
2819 return (subr->function.a1 (internal_args[0]));
2820 case 2:
2821 return (subr->function.a2
2822 (internal_args[0], internal_args[1]));
2823 case 3:
2824 return (subr->function.a3
2825 (internal_args[0], internal_args[1], internal_args[2]));
2826 case 4:
2827 return (subr->function.a4
2828 (internal_args[0], internal_args[1], internal_args[2],
2829 internal_args[3]));
2830 case 5:
2831 return (subr->function.a5
2832 (internal_args[0], internal_args[1], internal_args[2],
2833 internal_args[3], internal_args[4]));
2834 case 6:
2835 return (subr->function.a6
2836 (internal_args[0], internal_args[1], internal_args[2],
2837 internal_args[3], internal_args[4], internal_args[5]));
2838 case 7:
2839 return (subr->function.a7
2840 (internal_args[0], internal_args[1], internal_args[2],
2841 internal_args[3], internal_args[4], internal_args[5],
2842 internal_args[6]));
2843 case 8:
2844 return (subr->function.a8
2845 (internal_args[0], internal_args[1], internal_args[2],
2846 internal_args[3], internal_args[4], internal_args[5],
2847 internal_args[6], internal_args[7]));
2849 default:
2851 /* If a subr takes more than 8 arguments without using MANY
2852 or UNEVALLED, we need to extend this function to support it.
2853 Until this is done, there is no way to call the function. */
2854 emacs_abort ();
2859 static Lisp_Object
2860 apply_lambda (Lisp_Object fun, Lisp_Object args, ptrdiff_t count)
2862 Lisp_Object args_left;
2863 ptrdiff_t i;
2864 EMACS_INT numargs;
2865 Lisp_Object *arg_vector;
2866 Lisp_Object tem;
2867 USE_SAFE_ALLOCA;
2869 numargs = XFASTINT (Flength (args));
2870 SAFE_ALLOCA_LISP (arg_vector, numargs);
2871 args_left = args;
2873 for (i = 0; i < numargs; )
2875 tem = Fcar (args_left), args_left = Fcdr (args_left);
2876 tem = eval_sub (tem);
2877 arg_vector[i++] = tem;
2880 set_backtrace_args (specpdl + count, arg_vector, i);
2881 tem = funcall_lambda (fun, numargs, arg_vector);
2883 check_cons_list ();
2884 lisp_eval_depth--;
2885 /* Do the debug-on-exit now, while arg_vector still exists. */
2886 if (backtrace_debug_on_exit (specpdl + count))
2887 tem = call_debugger (list2 (Qexit, tem));
2888 SAFE_FREE ();
2889 specpdl_ptr--;
2890 return tem;
2893 /* Apply a Lisp function FUN to the NARGS evaluated arguments in ARG_VECTOR
2894 and return the result of evaluation.
2895 FUN must be either a lambda-expression, a compiled-code object,
2896 or a module function. */
2898 static Lisp_Object
2899 funcall_lambda (Lisp_Object fun, ptrdiff_t nargs,
2900 register Lisp_Object *arg_vector)
2902 Lisp_Object val, syms_left, next, lexenv;
2903 ptrdiff_t count = SPECPDL_INDEX ();
2904 ptrdiff_t i;
2905 bool optional, rest;
2907 if (CONSP (fun))
2909 if (EQ (XCAR (fun), Qclosure))
2911 Lisp_Object cdr = XCDR (fun); /* Drop `closure'. */
2912 if (! CONSP (cdr))
2913 xsignal1 (Qinvalid_function, fun);
2914 fun = cdr;
2915 lexenv = XCAR (fun);
2917 else
2918 lexenv = Qnil;
2919 syms_left = XCDR (fun);
2920 if (CONSP (syms_left))
2921 syms_left = XCAR (syms_left);
2922 else
2923 xsignal1 (Qinvalid_function, fun);
2925 else if (COMPILEDP (fun))
2927 ptrdiff_t size = PVSIZE (fun);
2928 if (size <= COMPILED_STACK_DEPTH)
2929 xsignal1 (Qinvalid_function, fun);
2930 syms_left = AREF (fun, COMPILED_ARGLIST);
2931 if (INTEGERP (syms_left))
2932 /* A byte-code object with an integer args template means we
2933 shouldn't bind any arguments, instead just call the byte-code
2934 interpreter directly; it will push arguments as necessary.
2936 Byte-code objects with a nil args template (the default)
2937 have dynamically-bound arguments, and use the
2938 argument-binding code below instead (as do all interpreted
2939 functions, even lexically bound ones). */
2941 /* If we have not actually read the bytecode string
2942 and constants vector yet, fetch them from the file. */
2943 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2944 Ffetch_bytecode (fun);
2945 return exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2946 AREF (fun, COMPILED_CONSTANTS),
2947 AREF (fun, COMPILED_STACK_DEPTH),
2948 syms_left,
2949 nargs, arg_vector);
2951 lexenv = Qnil;
2953 #ifdef HAVE_MODULES
2954 else if (MODULE_FUNCTIONP (fun))
2955 return funcall_module (XMODULE_FUNCTION (fun), nargs, arg_vector);
2956 #endif
2957 else
2958 emacs_abort ();
2960 i = optional = rest = 0;
2961 bool previous_optional_or_rest = false;
2962 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
2964 maybe_quit ();
2966 next = XCAR (syms_left);
2967 if (!SYMBOLP (next))
2968 xsignal1 (Qinvalid_function, fun);
2970 if (EQ (next, Qand_rest))
2972 if (rest || previous_optional_or_rest)
2973 xsignal1 (Qinvalid_function, fun);
2974 rest = 1;
2975 previous_optional_or_rest = true;
2977 else if (EQ (next, Qand_optional))
2979 if (optional || rest || previous_optional_or_rest)
2980 xsignal1 (Qinvalid_function, fun);
2981 optional = 1;
2982 previous_optional_or_rest = true;
2984 else
2986 Lisp_Object arg;
2987 if (rest)
2989 arg = Flist (nargs - i, &arg_vector[i]);
2990 i = nargs;
2992 else if (i < nargs)
2993 arg = arg_vector[i++];
2994 else if (!optional)
2995 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2996 else
2997 arg = Qnil;
2999 /* Bind the argument. */
3000 if (!NILP (lexenv) && SYMBOLP (next))
3001 /* Lexically bind NEXT by adding it to the lexenv alist. */
3002 lexenv = Fcons (Fcons (next, arg), lexenv);
3003 else
3004 /* Dynamically bind NEXT. */
3005 specbind (next, arg);
3006 previous_optional_or_rest = false;
3010 if (!NILP (syms_left) || previous_optional_or_rest)
3011 xsignal1 (Qinvalid_function, fun);
3012 else if (i < nargs)
3013 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
3015 if (!EQ (lexenv, Vinternal_interpreter_environment))
3016 /* Instantiate a new lexical environment. */
3017 specbind (Qinternal_interpreter_environment, lexenv);
3019 if (CONSP (fun))
3020 val = Fprogn (XCDR (XCDR (fun)));
3021 else
3023 /* If we have not actually read the bytecode string
3024 and constants vector yet, fetch them from the file. */
3025 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
3026 Ffetch_bytecode (fun);
3027 val = exec_byte_code (AREF (fun, COMPILED_BYTECODE),
3028 AREF (fun, COMPILED_CONSTANTS),
3029 AREF (fun, COMPILED_STACK_DEPTH),
3030 Qnil, 0, 0);
3033 return unbind_to (count, val);
3036 DEFUN ("func-arity", Ffunc_arity, Sfunc_arity, 1, 1, 0,
3037 doc: /* Return minimum and maximum number of args allowed for FUNCTION.
3038 FUNCTION must be a function of some kind.
3039 The returned value is a cons cell (MIN . MAX). MIN is the minimum number
3040 of args. MAX is the maximum number, or the symbol `many', for a
3041 function with `&rest' args, or `unevalled' for a special form. */)
3042 (Lisp_Object function)
3044 Lisp_Object original;
3045 Lisp_Object funcar;
3046 Lisp_Object result;
3048 original = function;
3050 retry:
3052 /* Optimize for no indirection. */
3053 function = original;
3054 if (SYMBOLP (function) && !NILP (function))
3056 function = XSYMBOL (function)->function;
3057 if (SYMBOLP (function))
3058 function = indirect_function (function);
3061 if (CONSP (function) && EQ (XCAR (function), Qmacro))
3062 function = XCDR (function);
3064 if (SUBRP (function))
3065 result = Fsubr_arity (function);
3066 else if (COMPILEDP (function))
3067 result = lambda_arity (function);
3068 #ifdef HAVE_MODULES
3069 else if (MODULE_FUNCTIONP (function))
3070 result = module_function_arity (XMODULE_FUNCTION (function));
3071 #endif
3072 else
3074 if (NILP (function))
3075 xsignal1 (Qvoid_function, original);
3076 if (!CONSP (function))
3077 xsignal1 (Qinvalid_function, original);
3078 funcar = XCAR (function);
3079 if (!SYMBOLP (funcar))
3080 xsignal1 (Qinvalid_function, original);
3081 if (EQ (funcar, Qlambda)
3082 || EQ (funcar, Qclosure))
3083 result = lambda_arity (function);
3084 else if (EQ (funcar, Qautoload))
3086 Fautoload_do_load (function, original, Qnil);
3087 goto retry;
3089 else
3090 xsignal1 (Qinvalid_function, original);
3092 return result;
3095 /* FUN must be either a lambda-expression or a compiled-code object. */
3096 static Lisp_Object
3097 lambda_arity (Lisp_Object fun)
3099 Lisp_Object syms_left;
3101 if (CONSP (fun))
3103 if (EQ (XCAR (fun), Qclosure))
3105 fun = XCDR (fun); /* Drop `closure'. */
3106 CHECK_CONS (fun);
3108 syms_left = XCDR (fun);
3109 if (CONSP (syms_left))
3110 syms_left = XCAR (syms_left);
3111 else
3112 xsignal1 (Qinvalid_function, fun);
3114 else if (COMPILEDP (fun))
3116 ptrdiff_t size = PVSIZE (fun);
3117 if (size <= COMPILED_STACK_DEPTH)
3118 xsignal1 (Qinvalid_function, fun);
3119 syms_left = AREF (fun, COMPILED_ARGLIST);
3120 if (INTEGERP (syms_left))
3121 return get_byte_code_arity (syms_left);
3123 else
3124 emacs_abort ();
3126 EMACS_INT minargs = 0, maxargs = 0;
3127 bool optional = false;
3128 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
3130 Lisp_Object next = XCAR (syms_left);
3131 if (!SYMBOLP (next))
3132 xsignal1 (Qinvalid_function, fun);
3134 if (EQ (next, Qand_rest))
3135 return Fcons (make_number (minargs), Qmany);
3136 else if (EQ (next, Qand_optional))
3137 optional = true;
3138 else
3140 if (!optional)
3141 minargs++;
3142 maxargs++;
3146 if (!NILP (syms_left))
3147 xsignal1 (Qinvalid_function, fun);
3149 return Fcons (make_number (minargs), make_number (maxargs));
3152 DEFUN ("fetch-bytecode", Ffetch_bytecode, Sfetch_bytecode,
3153 1, 1, 0,
3154 doc: /* If byte-compiled OBJECT is lazy-loaded, fetch it now. */)
3155 (Lisp_Object object)
3157 Lisp_Object tem;
3159 if (COMPILEDP (object))
3161 ptrdiff_t size = PVSIZE (object);
3162 if (size <= COMPILED_STACK_DEPTH)
3163 xsignal1 (Qinvalid_function, object);
3164 if (CONSP (AREF (object, COMPILED_BYTECODE)))
3166 tem = read_doc_string (AREF (object, COMPILED_BYTECODE));
3167 if (!CONSP (tem))
3169 tem = AREF (object, COMPILED_BYTECODE);
3170 if (CONSP (tem) && STRINGP (XCAR (tem)))
3171 error ("Invalid byte code in %s", SDATA (XCAR (tem)));
3172 else
3173 error ("Invalid byte code");
3175 ASET (object, COMPILED_BYTECODE, XCAR (tem));
3176 ASET (object, COMPILED_CONSTANTS, XCDR (tem));
3179 return object;
3182 /* Return true if SYMBOL currently has a let-binding
3183 which was made in the buffer that is now current. */
3185 bool
3186 let_shadows_buffer_binding_p (struct Lisp_Symbol *symbol)
3188 union specbinding *p;
3189 Lisp_Object buf = Fcurrent_buffer ();
3191 for (p = specpdl_ptr; p > specpdl; )
3192 if ((--p)->kind > SPECPDL_LET)
3194 struct Lisp_Symbol *let_bound_symbol = XSYMBOL (specpdl_symbol (p));
3195 eassert (let_bound_symbol->redirect != SYMBOL_VARALIAS);
3196 if (symbol == let_bound_symbol
3197 && EQ (specpdl_where (p), buf))
3198 return 1;
3201 return 0;
3204 static void
3205 do_specbind (struct Lisp_Symbol *sym, union specbinding *bind,
3206 Lisp_Object value, enum Set_Internal_Bind bindflag)
3208 switch (sym->redirect)
3210 case SYMBOL_PLAINVAL:
3211 if (!sym->trapped_write)
3212 SET_SYMBOL_VAL (sym, value);
3213 else
3214 set_internal (specpdl_symbol (bind), value, Qnil, bindflag);
3215 break;
3217 case SYMBOL_FORWARDED:
3218 if (BUFFER_OBJFWDP (SYMBOL_FWD (sym))
3219 && specpdl_kind (bind) == SPECPDL_LET_DEFAULT)
3221 set_default_internal (specpdl_symbol (bind), value, bindflag);
3222 return;
3224 FALLTHROUGH;
3225 case SYMBOL_LOCALIZED:
3226 set_internal (specpdl_symbol (bind), value, Qnil, bindflag);
3227 break;
3229 default:
3230 emacs_abort ();
3234 /* `specpdl_ptr' describes which variable is
3235 let-bound, so it can be properly undone when we unbind_to.
3236 It can be either a plain SPECPDL_LET or a SPECPDL_LET_LOCAL/DEFAULT.
3237 - SYMBOL is the variable being bound. Note that it should not be
3238 aliased (i.e. when let-binding V1 that's aliased to V2, we want
3239 to record V2 here).
3240 - WHERE tells us in which buffer the binding took place.
3241 This is used for SPECPDL_LET_LOCAL bindings (i.e. bindings to a
3242 buffer-local variable) as well as for SPECPDL_LET_DEFAULT bindings,
3243 i.e. bindings to the default value of a variable which can be
3244 buffer-local. */
3246 void
3247 specbind (Lisp_Object symbol, Lisp_Object value)
3249 struct Lisp_Symbol *sym;
3251 CHECK_SYMBOL (symbol);
3252 sym = XSYMBOL (symbol);
3254 start:
3255 switch (sym->redirect)
3257 case SYMBOL_VARALIAS:
3258 sym = indirect_variable (sym); XSETSYMBOL (symbol, sym); goto start;
3259 case SYMBOL_PLAINVAL:
3260 /* The most common case is that of a non-constant symbol with a
3261 trivial value. Make that as fast as we can. */
3262 specpdl_ptr->let.kind = SPECPDL_LET;
3263 specpdl_ptr->let.symbol = symbol;
3264 specpdl_ptr->let.old_value = SYMBOL_VAL (sym);
3265 specpdl_ptr->let.saved_value = Qnil;
3266 grow_specpdl ();
3267 do_specbind (sym, specpdl_ptr - 1, value, SET_INTERNAL_BIND);
3268 break;
3269 case SYMBOL_LOCALIZED:
3270 case SYMBOL_FORWARDED:
3272 Lisp_Object ovalue = find_symbol_value (symbol);
3273 specpdl_ptr->let.kind = SPECPDL_LET_LOCAL;
3274 specpdl_ptr->let.symbol = symbol;
3275 specpdl_ptr->let.old_value = ovalue;
3276 specpdl_ptr->let.where = Fcurrent_buffer ();
3277 specpdl_ptr->let.saved_value = Qnil;
3279 eassert (sym->redirect != SYMBOL_LOCALIZED
3280 || (EQ (SYMBOL_BLV (sym)->where, Fcurrent_buffer ())));
3282 if (sym->redirect == SYMBOL_LOCALIZED)
3284 if (!blv_found (SYMBOL_BLV (sym)))
3285 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3287 else if (BUFFER_OBJFWDP (SYMBOL_FWD (sym)))
3289 /* If SYMBOL is a per-buffer variable which doesn't have a
3290 buffer-local value here, make the `let' change the global
3291 value by changing the value of SYMBOL in all buffers not
3292 having their own value. This is consistent with what
3293 happens with other buffer-local variables. */
3294 if (NILP (Flocal_variable_p (symbol, Qnil)))
3296 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3297 grow_specpdl ();
3298 do_specbind (sym, specpdl_ptr - 1, value, SET_INTERNAL_BIND);
3299 return;
3302 else
3303 specpdl_ptr->let.kind = SPECPDL_LET;
3305 grow_specpdl ();
3306 do_specbind (sym, specpdl_ptr - 1, value, SET_INTERNAL_BIND);
3307 break;
3309 default: emacs_abort ();
3313 /* Push unwind-protect entries of various types. */
3315 void
3316 record_unwind_protect (void (*function) (Lisp_Object), Lisp_Object arg)
3318 specpdl_ptr->unwind.kind = SPECPDL_UNWIND;
3319 specpdl_ptr->unwind.func = function;
3320 specpdl_ptr->unwind.arg = arg;
3321 grow_specpdl ();
3324 void
3325 record_unwind_protect_ptr (void (*function) (void *), void *arg)
3327 specpdl_ptr->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3328 specpdl_ptr->unwind_ptr.func = function;
3329 specpdl_ptr->unwind_ptr.arg = arg;
3330 grow_specpdl ();
3333 void
3334 record_unwind_protect_int (void (*function) (int), int arg)
3336 specpdl_ptr->unwind_int.kind = SPECPDL_UNWIND_INT;
3337 specpdl_ptr->unwind_int.func = function;
3338 specpdl_ptr->unwind_int.arg = arg;
3339 grow_specpdl ();
3342 void
3343 record_unwind_protect_void (void (*function) (void))
3345 specpdl_ptr->unwind_void.kind = SPECPDL_UNWIND_VOID;
3346 specpdl_ptr->unwind_void.func = function;
3347 grow_specpdl ();
3350 void
3351 rebind_for_thread_switch (void)
3353 union specbinding *bind;
3355 for (bind = specpdl; bind != specpdl_ptr; ++bind)
3357 if (bind->kind >= SPECPDL_LET)
3359 Lisp_Object value = specpdl_saved_value (bind);
3360 Lisp_Object sym = specpdl_symbol (bind);
3361 bind->let.saved_value = Qnil;
3362 do_specbind (XSYMBOL (sym), bind, value,
3363 SET_INTERNAL_THREAD_SWITCH);
3368 static void
3369 do_one_unbind (union specbinding *this_binding, bool unwinding,
3370 enum Set_Internal_Bind bindflag)
3372 eassert (unwinding || this_binding->kind >= SPECPDL_LET);
3373 switch (this_binding->kind)
3375 case SPECPDL_UNWIND:
3376 this_binding->unwind.func (this_binding->unwind.arg);
3377 break;
3378 case SPECPDL_UNWIND_PTR:
3379 this_binding->unwind_ptr.func (this_binding->unwind_ptr.arg);
3380 break;
3381 case SPECPDL_UNWIND_INT:
3382 this_binding->unwind_int.func (this_binding->unwind_int.arg);
3383 break;
3384 case SPECPDL_UNWIND_VOID:
3385 this_binding->unwind_void.func ();
3386 break;
3387 case SPECPDL_BACKTRACE:
3388 break;
3389 case SPECPDL_LET:
3390 { /* If variable has a trivial value (no forwarding), and isn't
3391 trapped, we can just set it. */
3392 Lisp_Object sym = specpdl_symbol (this_binding);
3393 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3395 if (XSYMBOL (sym)->trapped_write == SYMBOL_UNTRAPPED_WRITE)
3396 SET_SYMBOL_VAL (XSYMBOL (sym), specpdl_old_value (this_binding));
3397 else
3398 set_internal (sym, specpdl_old_value (this_binding),
3399 Qnil, bindflag);
3400 break;
3403 /* Come here only if make_local_foo was used for the first time
3404 on this var within this let. */
3405 FALLTHROUGH;
3406 case SPECPDL_LET_DEFAULT:
3407 set_default_internal (specpdl_symbol (this_binding),
3408 specpdl_old_value (this_binding),
3409 bindflag);
3410 break;
3411 case SPECPDL_LET_LOCAL:
3413 Lisp_Object symbol = specpdl_symbol (this_binding);
3414 Lisp_Object where = specpdl_where (this_binding);
3415 Lisp_Object old_value = specpdl_old_value (this_binding);
3416 eassert (BUFFERP (where));
3418 /* If this was a local binding, reset the value in the appropriate
3419 buffer, but only if that buffer's binding still exists. */
3420 if (!NILP (Flocal_variable_p (symbol, where)))
3421 set_internal (symbol, old_value, where, bindflag);
3423 break;
3427 static void
3428 do_nothing (void)
3431 /* Push an unwind-protect entry that does nothing, so that
3432 set_unwind_protect_ptr can overwrite it later. */
3434 void
3435 record_unwind_protect_nothing (void)
3437 record_unwind_protect_void (do_nothing);
3440 /* Clear the unwind-protect entry COUNT, so that it does nothing.
3441 It need not be at the top of the stack. */
3443 void
3444 clear_unwind_protect (ptrdiff_t count)
3446 union specbinding *p = specpdl + count;
3447 p->unwind_void.kind = SPECPDL_UNWIND_VOID;
3448 p->unwind_void.func = do_nothing;
3451 /* Set the unwind-protect entry COUNT so that it invokes FUNC (ARG).
3452 It need not be at the top of the stack. Discard the entry's
3453 previous value without invoking it. */
3455 void
3456 set_unwind_protect (ptrdiff_t count, void (*func) (Lisp_Object),
3457 Lisp_Object arg)
3459 union specbinding *p = specpdl + count;
3460 p->unwind.kind = SPECPDL_UNWIND;
3461 p->unwind.func = func;
3462 p->unwind.arg = arg;
3465 void
3466 set_unwind_protect_ptr (ptrdiff_t count, void (*func) (void *), void *arg)
3468 union specbinding *p = specpdl + count;
3469 p->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3470 p->unwind_ptr.func = func;
3471 p->unwind_ptr.arg = arg;
3474 /* Pop and execute entries from the unwind-protect stack until the
3475 depth COUNT is reached. Return VALUE. */
3477 Lisp_Object
3478 unbind_to (ptrdiff_t count, Lisp_Object value)
3480 Lisp_Object quitf = Vquit_flag;
3482 Vquit_flag = Qnil;
3484 while (specpdl_ptr != specpdl + count)
3486 /* Copy the binding, and decrement specpdl_ptr, before we do
3487 the work to unbind it. We decrement first
3488 so that an error in unbinding won't try to unbind
3489 the same entry again, and we copy the binding first
3490 in case more bindings are made during some of the code we run. */
3492 union specbinding this_binding;
3493 this_binding = *--specpdl_ptr;
3495 do_one_unbind (&this_binding, true, SET_INTERNAL_UNBIND);
3498 if (NILP (Vquit_flag) && !NILP (quitf))
3499 Vquit_flag = quitf;
3501 return value;
3504 void
3505 unbind_for_thread_switch (struct thread_state *thr)
3507 union specbinding *bind;
3509 for (bind = thr->m_specpdl_ptr; bind > thr->m_specpdl;)
3511 if ((--bind)->kind >= SPECPDL_LET)
3513 Lisp_Object sym = specpdl_symbol (bind);
3514 bind->let.saved_value = find_symbol_value (sym);
3515 do_one_unbind (bind, false, SET_INTERNAL_THREAD_SWITCH);
3520 DEFUN ("special-variable-p", Fspecial_variable_p, Sspecial_variable_p, 1, 1, 0,
3521 doc: /* Return non-nil if SYMBOL's global binding has been declared special.
3522 A special variable is one that will be bound dynamically, even in a
3523 context where binding is lexical by default. */)
3524 (Lisp_Object symbol)
3526 CHECK_SYMBOL (symbol);
3527 return XSYMBOL (symbol)->declared_special ? Qt : Qnil;
3531 static union specbinding *
3532 get_backtrace_starting_at (Lisp_Object base)
3534 union specbinding *pdl = backtrace_top ();
3536 if (!NILP (base))
3537 { /* Skip up to `base'. */
3538 base = Findirect_function (base, Qt);
3539 while (backtrace_p (pdl)
3540 && !EQ (base, Findirect_function (backtrace_function (pdl), Qt)))
3541 pdl = backtrace_next (pdl);
3544 return pdl;
3547 static union specbinding *
3548 get_backtrace_frame (Lisp_Object nframes, Lisp_Object base)
3550 register EMACS_INT i;
3552 CHECK_NATNUM (nframes);
3553 union specbinding *pdl = get_backtrace_starting_at (base);
3555 /* Find the frame requested. */
3556 for (i = XFASTINT (nframes); i > 0 && backtrace_p (pdl); i--)
3557 pdl = backtrace_next (pdl);
3559 return pdl;
3562 static Lisp_Object
3563 backtrace_frame_apply (Lisp_Object function, union specbinding *pdl)
3565 if (!backtrace_p (pdl))
3566 return Qnil;
3568 Lisp_Object flags = Qnil;
3569 if (backtrace_debug_on_exit (pdl))
3570 flags = Fcons (QCdebug_on_exit, Fcons (Qt, Qnil));
3572 if (backtrace_nargs (pdl) == UNEVALLED)
3573 return call4 (function, Qnil, backtrace_function (pdl), *backtrace_args (pdl), flags);
3574 else
3576 Lisp_Object tem = Flist (backtrace_nargs (pdl), backtrace_args (pdl));
3577 return call4 (function, Qt, backtrace_function (pdl), tem, flags);
3581 DEFUN ("backtrace-debug", Fbacktrace_debug, Sbacktrace_debug, 2, 2, 0,
3582 doc: /* Set the debug-on-exit flag of eval frame LEVEL levels down to FLAG.
3583 The debugger is entered when that frame exits, if the flag is non-nil. */)
3584 (Lisp_Object level, Lisp_Object flag)
3586 CHECK_NUMBER (level);
3587 union specbinding *pdl = get_backtrace_frame(level, Qnil);
3589 if (backtrace_p (pdl))
3590 set_backtrace_debug_on_exit (pdl, !NILP (flag));
3592 return flag;
3595 DEFUN ("mapbacktrace", Fmapbacktrace, Smapbacktrace, 1, 2, 0,
3596 doc: /* Call FUNCTION for each frame in backtrace.
3597 If BASE is non-nil, it should be a function and iteration will start
3598 from its nearest activation frame.
3599 FUNCTION is called with 4 arguments: EVALD, FUNC, ARGS, and FLAGS. If
3600 a frame has not evaluated its arguments yet or is a special form,
3601 EVALD is nil and ARGS is a list of forms. If a frame has evaluated
3602 its arguments and called its function already, EVALD is t and ARGS is
3603 a list of values.
3604 FLAGS is a plist of properties of the current frame: currently, the
3605 only supported property is :debug-on-exit. `mapbacktrace' always
3606 returns nil. */)
3607 (Lisp_Object function, Lisp_Object base)
3609 union specbinding *pdl = get_backtrace_starting_at (base);
3611 while (backtrace_p (pdl))
3613 backtrace_frame_apply (function, pdl);
3614 pdl = backtrace_next (pdl);
3617 return Qnil;
3620 DEFUN ("backtrace-frame--internal", Fbacktrace_frame_internal,
3621 Sbacktrace_frame_internal, 3, 3, NULL,
3622 doc: /* Call FUNCTION on stack frame NFRAMES away from BASE.
3623 Return the result of FUNCTION, or nil if no matching frame could be found. */)
3624 (Lisp_Object function, Lisp_Object nframes, Lisp_Object base)
3626 return backtrace_frame_apply (function, get_backtrace_frame (nframes, base));
3629 /* For backtrace-eval, we want to temporarily unwind the last few elements of
3630 the specpdl stack, and then rewind them. We store the pre-unwind values
3631 directly in the pre-existing specpdl elements (i.e. we swap the current
3632 value and the old value stored in the specpdl), kind of like the inplace
3633 pointer-reversal trick. As it turns out, the rewind does the same as the
3634 unwind, except it starts from the other end of the specpdl stack, so we use
3635 the same function for both unwind and rewind. */
3636 static void
3637 backtrace_eval_unrewind (int distance)
3639 union specbinding *tmp = specpdl_ptr;
3640 int step = -1;
3641 if (distance < 0)
3642 { /* It's a rewind rather than unwind. */
3643 tmp += distance - 1;
3644 step = 1;
3645 distance = -distance;
3648 for (; distance > 0; distance--)
3650 tmp += step;
3651 switch (tmp->kind)
3653 /* FIXME: Ideally we'd like to "temporarily unwind" (some of) those
3654 unwind_protect, but the problem is that we don't know how to
3655 rewind them afterwards. */
3656 case SPECPDL_UNWIND:
3658 Lisp_Object oldarg = tmp->unwind.arg;
3659 if (tmp->unwind.func == set_buffer_if_live)
3660 tmp->unwind.arg = Fcurrent_buffer ();
3661 else if (tmp->unwind.func == save_excursion_restore)
3662 tmp->unwind.arg = save_excursion_save ();
3663 else
3664 break;
3665 tmp->unwind.func (oldarg);
3666 break;
3669 case SPECPDL_UNWIND_PTR:
3670 case SPECPDL_UNWIND_INT:
3671 case SPECPDL_UNWIND_VOID:
3672 case SPECPDL_BACKTRACE:
3673 break;
3674 case SPECPDL_LET:
3675 { /* If variable has a trivial value (no forwarding), we can
3676 just set it. No need to check for constant symbols here,
3677 since that was already done by specbind. */
3678 Lisp_Object sym = specpdl_symbol (tmp);
3679 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3681 Lisp_Object old_value = specpdl_old_value (tmp);
3682 set_specpdl_old_value (tmp, SYMBOL_VAL (XSYMBOL (sym)));
3683 SET_SYMBOL_VAL (XSYMBOL (sym), old_value);
3684 break;
3687 /* Come here only if make_local_foo was used for the first
3688 time on this var within this let. */
3689 FALLTHROUGH;
3690 case SPECPDL_LET_DEFAULT:
3692 Lisp_Object sym = specpdl_symbol (tmp);
3693 Lisp_Object old_value = specpdl_old_value (tmp);
3694 set_specpdl_old_value (tmp, Fdefault_value (sym));
3695 Fset_default (sym, old_value);
3697 break;
3698 case SPECPDL_LET_LOCAL:
3700 Lisp_Object symbol = specpdl_symbol (tmp);
3701 Lisp_Object where = specpdl_where (tmp);
3702 Lisp_Object old_value = specpdl_old_value (tmp);
3703 eassert (BUFFERP (where));
3705 /* If this was a local binding, reset the value in the appropriate
3706 buffer, but only if that buffer's binding still exists. */
3707 if (!NILP (Flocal_variable_p (symbol, where)))
3709 set_specpdl_old_value
3710 (tmp, Fbuffer_local_value (symbol, where));
3711 set_internal (symbol, old_value, where, SET_INTERNAL_UNBIND);
3714 break;
3719 DEFUN ("backtrace-eval", Fbacktrace_eval, Sbacktrace_eval, 2, 3, NULL,
3720 doc: /* Evaluate EXP in the context of some activation frame.
3721 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3722 (Lisp_Object exp, Lisp_Object nframes, Lisp_Object base)
3724 union specbinding *pdl = get_backtrace_frame (nframes, base);
3725 ptrdiff_t count = SPECPDL_INDEX ();
3726 ptrdiff_t distance = specpdl_ptr - pdl;
3727 eassert (distance >= 0);
3729 if (!backtrace_p (pdl))
3730 error ("Activation frame not found!");
3732 backtrace_eval_unrewind (distance);
3733 record_unwind_protect_int (backtrace_eval_unrewind, -distance);
3735 /* Use eval_sub rather than Feval since the main motivation behind
3736 backtrace-eval is to be able to get/set the value of lexical variables
3737 from the debugger. */
3738 return unbind_to (count, eval_sub (exp));
3741 DEFUN ("backtrace--locals", Fbacktrace__locals, Sbacktrace__locals, 1, 2, NULL,
3742 doc: /* Return names and values of local variables of a stack frame.
3743 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3744 (Lisp_Object nframes, Lisp_Object base)
3746 union specbinding *frame = get_backtrace_frame (nframes, base);
3747 union specbinding *prevframe
3748 = get_backtrace_frame (make_number (XFASTINT (nframes) - 1), base);
3749 ptrdiff_t distance = specpdl_ptr - frame;
3750 Lisp_Object result = Qnil;
3751 eassert (distance >= 0);
3753 if (!backtrace_p (prevframe))
3754 error ("Activation frame not found!");
3755 if (!backtrace_p (frame))
3756 error ("Activation frame not found!");
3758 /* The specpdl entries normally contain the symbol being bound along with its
3759 `old_value', so it can be restored. The new value to which it is bound is
3760 available in one of two places: either in the current value of the
3761 variable (if it hasn't been rebound yet) or in the `old_value' slot of the
3762 next specpdl entry for it.
3763 `backtrace_eval_unrewind' happens to swap the role of `old_value'
3764 and "new value", so we abuse it here, to fetch the new value.
3765 It's ugly (we'd rather not modify global data) and a bit inefficient,
3766 but it does the job for now. */
3767 backtrace_eval_unrewind (distance);
3769 /* Grab values. */
3771 union specbinding *tmp = prevframe;
3772 for (; tmp > frame; tmp--)
3774 switch (tmp->kind)
3776 case SPECPDL_LET:
3777 case SPECPDL_LET_DEFAULT:
3778 case SPECPDL_LET_LOCAL:
3780 Lisp_Object sym = specpdl_symbol (tmp);
3781 Lisp_Object val = specpdl_old_value (tmp);
3782 if (EQ (sym, Qinternal_interpreter_environment))
3784 Lisp_Object env = val;
3785 for (; CONSP (env); env = XCDR (env))
3787 Lisp_Object binding = XCAR (env);
3788 if (CONSP (binding))
3789 result = Fcons (Fcons (XCAR (binding),
3790 XCDR (binding)),
3791 result);
3794 else
3795 result = Fcons (Fcons (sym, val), result);
3797 break;
3799 case SPECPDL_UNWIND:
3800 case SPECPDL_UNWIND_PTR:
3801 case SPECPDL_UNWIND_INT:
3802 case SPECPDL_UNWIND_VOID:
3803 case SPECPDL_BACKTRACE:
3804 break;
3806 default:
3807 emacs_abort ();
3812 /* Restore values from specpdl to original place. */
3813 backtrace_eval_unrewind (-distance);
3815 return result;
3819 void
3820 mark_specpdl (union specbinding *first, union specbinding *ptr)
3822 union specbinding *pdl;
3823 for (pdl = first; pdl != ptr; pdl++)
3825 switch (pdl->kind)
3827 case SPECPDL_UNWIND:
3828 mark_object (specpdl_arg (pdl));
3829 break;
3831 case SPECPDL_BACKTRACE:
3833 ptrdiff_t nargs = backtrace_nargs (pdl);
3834 mark_object (backtrace_function (pdl));
3835 if (nargs == UNEVALLED)
3836 nargs = 1;
3837 while (nargs--)
3838 mark_object (backtrace_args (pdl)[nargs]);
3840 break;
3842 case SPECPDL_LET_DEFAULT:
3843 case SPECPDL_LET_LOCAL:
3844 mark_object (specpdl_where (pdl));
3845 FALLTHROUGH;
3846 case SPECPDL_LET:
3847 mark_object (specpdl_symbol (pdl));
3848 mark_object (specpdl_old_value (pdl));
3849 mark_object (specpdl_saved_value (pdl));
3850 break;
3852 case SPECPDL_UNWIND_PTR:
3853 case SPECPDL_UNWIND_INT:
3854 case SPECPDL_UNWIND_VOID:
3855 break;
3857 default:
3858 emacs_abort ();
3863 void
3864 get_backtrace (Lisp_Object array)
3866 union specbinding *pdl = backtrace_next (backtrace_top ());
3867 ptrdiff_t i = 0, asize = ASIZE (array);
3869 /* Copy the backtrace contents into working memory. */
3870 for (; i < asize; i++)
3872 if (backtrace_p (pdl))
3874 ASET (array, i, backtrace_function (pdl));
3875 pdl = backtrace_next (pdl);
3877 else
3878 ASET (array, i, Qnil);
3882 Lisp_Object backtrace_top_function (void)
3884 union specbinding *pdl = backtrace_top ();
3885 return (backtrace_p (pdl) ? backtrace_function (pdl) : Qnil);
3888 void
3889 syms_of_eval (void)
3891 DEFVAR_INT ("max-specpdl-size", max_specpdl_size,
3892 doc: /* Limit on number of Lisp variable bindings and `unwind-protect's.
3893 If Lisp code tries to increase the total number past this amount,
3894 an error is signaled.
3895 You can safely use a value considerably larger than the default value,
3896 if that proves inconveniently small. However, if you increase it too far,
3897 Emacs could run out of memory trying to make the stack bigger.
3898 Note that this limit may be silently increased by the debugger
3899 if `debug-on-error' or `debug-on-quit' is set. */);
3901 DEFVAR_INT ("max-lisp-eval-depth", max_lisp_eval_depth,
3902 doc: /* Limit on depth in `eval', `apply' and `funcall' before error.
3904 This limit serves to catch infinite recursions for you before they cause
3905 actual stack overflow in C, which would be fatal for Emacs.
3906 You can safely make it considerably larger than its default value,
3907 if that proves inconveniently small. However, if you increase it too far,
3908 Emacs could overflow the real C stack, and crash. */);
3910 DEFVAR_LISP ("quit-flag", Vquit_flag,
3911 doc: /* Non-nil causes `eval' to abort, unless `inhibit-quit' is non-nil.
3912 If the value is t, that means do an ordinary quit.
3913 If the value equals `throw-on-input', that means quit by throwing
3914 to the tag specified in `throw-on-input'; it's for handling `while-no-input'.
3915 Typing C-g sets `quit-flag' to t, regardless of `inhibit-quit',
3916 but `inhibit-quit' non-nil prevents anything from taking notice of that. */);
3917 Vquit_flag = Qnil;
3919 DEFVAR_LISP ("inhibit-quit", Vinhibit_quit,
3920 doc: /* Non-nil inhibits C-g quitting from happening immediately.
3921 Note that `quit-flag' will still be set by typing C-g,
3922 so a quit will be signaled as soon as `inhibit-quit' is nil.
3923 To prevent this happening, set `quit-flag' to nil
3924 before making `inhibit-quit' nil. */);
3925 Vinhibit_quit = Qnil;
3927 DEFSYM (Qsetq, "setq");
3928 DEFSYM (Qinhibit_quit, "inhibit-quit");
3929 DEFSYM (Qautoload, "autoload");
3930 DEFSYM (Qinhibit_debugger, "inhibit-debugger");
3931 DEFSYM (Qmacro, "macro");
3933 /* Note that the process handling also uses Qexit, but we don't want
3934 to staticpro it twice, so we just do it here. */
3935 DEFSYM (Qexit, "exit");
3937 DEFSYM (Qinteractive, "interactive");
3938 DEFSYM (Qcommandp, "commandp");
3939 DEFSYM (Qand_rest, "&rest");
3940 DEFSYM (Qand_optional, "&optional");
3941 DEFSYM (Qclosure, "closure");
3942 DEFSYM (QCdocumentation, ":documentation");
3943 DEFSYM (Qdebug, "debug");
3945 DEFVAR_LISP ("inhibit-debugger", Vinhibit_debugger,
3946 doc: /* Non-nil means never enter the debugger.
3947 Normally set while the debugger is already active, to avoid recursive
3948 invocations. */);
3949 Vinhibit_debugger = Qnil;
3951 DEFVAR_LISP ("debug-on-error", Vdebug_on_error,
3952 doc: /* Non-nil means enter debugger if an error is signaled.
3953 Does not apply to errors handled by `condition-case' or those
3954 matched by `debug-ignored-errors'.
3955 If the value is a list, an error only means to enter the debugger
3956 if one of its condition symbols appears in the list.
3957 When you evaluate an expression interactively, this variable
3958 is temporarily non-nil if `eval-expression-debug-on-error' is non-nil.
3959 The command `toggle-debug-on-error' toggles this.
3960 See also the variable `debug-on-quit' and `inhibit-debugger'. */);
3961 Vdebug_on_error = Qnil;
3963 DEFVAR_LISP ("debug-ignored-errors", Vdebug_ignored_errors,
3964 doc: /* List of errors for which the debugger should not be called.
3965 Each element may be a condition-name or a regexp that matches error messages.
3966 If any element applies to a given error, that error skips the debugger
3967 and just returns to top level.
3968 This overrides the variable `debug-on-error'.
3969 It does not apply to errors handled by `condition-case'. */);
3970 Vdebug_ignored_errors = Qnil;
3972 DEFVAR_BOOL ("debug-on-quit", debug_on_quit,
3973 doc: /* Non-nil means enter debugger if quit is signaled (C-g, for example).
3974 Does not apply if quit is handled by a `condition-case'. */);
3975 debug_on_quit = 0;
3977 DEFVAR_BOOL ("debug-on-next-call", debug_on_next_call,
3978 doc: /* Non-nil means enter debugger before next `eval', `apply' or `funcall'. */);
3980 DEFVAR_BOOL ("debugger-may-continue", debugger_may_continue,
3981 doc: /* Non-nil means debugger may continue execution.
3982 This is nil when the debugger is called under circumstances where it
3983 might not be safe to continue. */);
3984 debugger_may_continue = 1;
3986 DEFVAR_BOOL ("debugger-stack-frame-as-list", debugger_stack_frame_as_list,
3987 doc: /* Non-nil means display call stack frames as lists. */);
3988 debugger_stack_frame_as_list = 0;
3990 DEFVAR_LISP ("debugger", Vdebugger,
3991 doc: /* Function to call to invoke debugger.
3992 If due to frame exit, args are `exit' and the value being returned;
3993 this function's value will be returned instead of that.
3994 If due to error, args are `error' and a list of the args to `signal'.
3995 If due to `apply' or `funcall' entry, one arg, `lambda'.
3996 If due to `eval' entry, one arg, t. */);
3997 Vdebugger = Qnil;
3999 DEFVAR_LISP ("signal-hook-function", Vsignal_hook_function,
4000 doc: /* If non-nil, this is a function for `signal' to call.
4001 It receives the same arguments that `signal' was given.
4002 The Edebug package uses this to regain control. */);
4003 Vsignal_hook_function = Qnil;
4005 DEFVAR_LISP ("debug-on-signal", Vdebug_on_signal,
4006 doc: /* Non-nil means call the debugger regardless of condition handlers.
4007 Note that `debug-on-error', `debug-on-quit' and friends
4008 still determine whether to handle the particular condition. */);
4009 Vdebug_on_signal = Qnil;
4011 /* When lexical binding is being used,
4012 Vinternal_interpreter_environment is non-nil, and contains an alist
4013 of lexically-bound variable, or (t), indicating an empty
4014 environment. The lisp name of this variable would be
4015 `internal-interpreter-environment' if it weren't hidden.
4016 Every element of this list can be either a cons (VAR . VAL)
4017 specifying a lexical binding, or a single symbol VAR indicating
4018 that this variable should use dynamic scoping. */
4019 DEFSYM (Qinternal_interpreter_environment,
4020 "internal-interpreter-environment");
4021 DEFVAR_LISP ("internal-interpreter-environment",
4022 Vinternal_interpreter_environment,
4023 doc: /* If non-nil, the current lexical environment of the lisp interpreter.
4024 When lexical binding is not being used, this variable is nil.
4025 A value of `(t)' indicates an empty environment, otherwise it is an
4026 alist of active lexical bindings. */);
4027 Vinternal_interpreter_environment = Qnil;
4028 /* Don't export this variable to Elisp, so no one can mess with it
4029 (Just imagine if someone makes it buffer-local). */
4030 Funintern (Qinternal_interpreter_environment, Qnil);
4032 Vrun_hooks = intern_c_string ("run-hooks");
4033 staticpro (&Vrun_hooks);
4035 staticpro (&Vautoload_queue);
4036 Vautoload_queue = Qnil;
4037 staticpro (&Vsignaling_function);
4038 Vsignaling_function = Qnil;
4040 inhibit_lisp_code = Qnil;
4042 defsubr (&Sor);
4043 defsubr (&Sand);
4044 defsubr (&Sif);
4045 defsubr (&Scond);
4046 defsubr (&Sprogn);
4047 defsubr (&Sprog1);
4048 defsubr (&Sprog2);
4049 defsubr (&Ssetq);
4050 defsubr (&Squote);
4051 defsubr (&Sfunction);
4052 defsubr (&Sdefault_toplevel_value);
4053 defsubr (&Sset_default_toplevel_value);
4054 defsubr (&Sdefvar);
4055 defsubr (&Sdefvaralias);
4056 DEFSYM (Qdefvaralias, "defvaralias");
4057 defsubr (&Sdefconst);
4058 defsubr (&Smake_var_non_special);
4059 defsubr (&Slet);
4060 defsubr (&SletX);
4061 defsubr (&Swhile);
4062 defsubr (&Smacroexpand);
4063 defsubr (&Scatch);
4064 defsubr (&Sthrow);
4065 defsubr (&Sunwind_protect);
4066 defsubr (&Scondition_case);
4067 defsubr (&Ssignal);
4068 defsubr (&Scommandp);
4069 defsubr (&Sautoload);
4070 defsubr (&Sautoload_do_load);
4071 defsubr (&Seval);
4072 defsubr (&Sapply);
4073 defsubr (&Sfuncall);
4074 defsubr (&Sfunc_arity);
4075 defsubr (&Srun_hooks);
4076 defsubr (&Srun_hook_with_args);
4077 defsubr (&Srun_hook_with_args_until_success);
4078 defsubr (&Srun_hook_with_args_until_failure);
4079 defsubr (&Srun_hook_wrapped);
4080 defsubr (&Sfetch_bytecode);
4081 defsubr (&Sbacktrace_debug);
4082 DEFSYM (QCdebug_on_exit, ":debug-on-exit");
4083 defsubr (&Smapbacktrace);
4084 defsubr (&Sbacktrace_frame_internal);
4085 defsubr (&Sbacktrace_eval);
4086 defsubr (&Sbacktrace__locals);
4087 defsubr (&Sspecial_variable_p);
4088 defsubr (&Sfunctionp);