Tune interpretation of integer arglist descriptor
[emacs.git] / src / eval.c
blob7b7bdd8df7b1eef5e0d685ed57e1dbbc0895e73b
1 /* Evaluator for GNU Emacs Lisp interpreter.
3 Copyright (C) 1985-1987, 1993-1995, 1999-2016 Free Software Foundation,
4 Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
23 #include <limits.h>
24 #include <stdio.h>
25 #include "lisp.h"
26 #include "blockinput.h"
27 #include "commands.h"
28 #include "keyboard.h"
29 #include "dispextern.h"
30 #include "buffer.h"
32 /* Chain of condition and catch handlers currently in effect. */
34 struct handler *handlerlist;
36 /* Non-nil means record all fset's and provide's, to be undone
37 if the file being autoloaded is not fully loaded.
38 They are recorded by being consed onto the front of Vautoload_queue:
39 (FUN . ODEF) for a defun, (0 . OFEATURES) for a provide. */
41 Lisp_Object Vautoload_queue;
43 /* This holds either the symbol `run-hooks' or nil.
44 It is nil at an early stage of startup, and when Emacs
45 is shutting down. */
46 Lisp_Object Vrun_hooks;
48 /* Current number of specbindings allocated in specpdl, not counting
49 the dummy entry specpdl[-1]. */
51 ptrdiff_t specpdl_size;
53 /* Pointer to beginning of specpdl. A dummy entry specpdl[-1] exists
54 only so that its address can be taken. */
56 union specbinding *specpdl;
58 /* Pointer to first unused element in specpdl. */
60 union specbinding *specpdl_ptr;
62 /* Depth in Lisp evaluations and function calls. */
64 static EMACS_INT lisp_eval_depth;
66 /* The value of num_nonmacro_input_events as of the last time we
67 started to enter the debugger. If we decide to enter the debugger
68 again when this is still equal to num_nonmacro_input_events, then we
69 know that the debugger itself has an error, and we should just
70 signal the error instead of entering an infinite loop of debugger
71 invocations. */
73 static EMACS_INT when_entered_debugger;
75 /* The function from which the last `signal' was called. Set in
76 Fsignal. */
77 /* FIXME: We should probably get rid of this! */
78 Lisp_Object Vsignaling_function;
80 /* If non-nil, Lisp code must not be run since some part of Emacs is in
81 an inconsistent state. Currently unused. */
82 Lisp_Object inhibit_lisp_code;
84 /* These would ordinarily be static, but they need to be visible to GDB. */
85 bool backtrace_p (union specbinding *) EXTERNALLY_VISIBLE;
86 Lisp_Object *backtrace_args (union specbinding *) EXTERNALLY_VISIBLE;
87 Lisp_Object backtrace_function (union specbinding *) EXTERNALLY_VISIBLE;
88 union specbinding *backtrace_next (union specbinding *) EXTERNALLY_VISIBLE;
89 union specbinding *backtrace_top (void) EXTERNALLY_VISIBLE;
91 static Lisp_Object funcall_lambda (Lisp_Object, ptrdiff_t, Lisp_Object *);
92 static Lisp_Object apply_lambda (Lisp_Object, Lisp_Object, ptrdiff_t);
93 static Lisp_Object lambda_arity (Lisp_Object);
95 static Lisp_Object
96 specpdl_symbol (union specbinding *pdl)
98 eassert (pdl->kind >= SPECPDL_LET);
99 return pdl->let.symbol;
102 static Lisp_Object
103 specpdl_old_value (union specbinding *pdl)
105 eassert (pdl->kind >= SPECPDL_LET);
106 return pdl->let.old_value;
109 static void
110 set_specpdl_old_value (union specbinding *pdl, Lisp_Object val)
112 eassert (pdl->kind >= SPECPDL_LET);
113 pdl->let.old_value = val;
116 static Lisp_Object
117 specpdl_where (union specbinding *pdl)
119 eassert (pdl->kind > SPECPDL_LET);
120 return pdl->let.where;
123 static Lisp_Object
124 specpdl_arg (union specbinding *pdl)
126 eassert (pdl->kind == SPECPDL_UNWIND);
127 return pdl->unwind.arg;
130 Lisp_Object
131 backtrace_function (union specbinding *pdl)
133 eassert (pdl->kind == SPECPDL_BACKTRACE);
134 return pdl->bt.function;
137 static ptrdiff_t
138 backtrace_nargs (union specbinding *pdl)
140 eassert (pdl->kind == SPECPDL_BACKTRACE);
141 return pdl->bt.nargs;
144 Lisp_Object *
145 backtrace_args (union specbinding *pdl)
147 eassert (pdl->kind == SPECPDL_BACKTRACE);
148 return pdl->bt.args;
151 static bool
152 backtrace_debug_on_exit (union specbinding *pdl)
154 eassert (pdl->kind == SPECPDL_BACKTRACE);
155 return pdl->bt.debug_on_exit;
158 /* Functions to modify slots of backtrace records. */
160 static void
161 set_backtrace_args (union specbinding *pdl, Lisp_Object *args, ptrdiff_t nargs)
163 eassert (pdl->kind == SPECPDL_BACKTRACE);
164 pdl->bt.args = args;
165 pdl->bt.nargs = nargs;
168 static void
169 set_backtrace_debug_on_exit (union specbinding *pdl, bool doe)
171 eassert (pdl->kind == SPECPDL_BACKTRACE);
172 pdl->bt.debug_on_exit = doe;
175 /* Helper functions to scan the backtrace. */
177 bool
178 backtrace_p (union specbinding *pdl)
179 { return pdl >= specpdl; }
181 union specbinding *
182 backtrace_top (void)
184 union specbinding *pdl = specpdl_ptr - 1;
185 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
186 pdl--;
187 return pdl;
190 union specbinding *
191 backtrace_next (union specbinding *pdl)
193 pdl--;
194 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
195 pdl--;
196 return pdl;
199 /* Return a pointer to somewhere near the top of the C stack. */
200 void *
201 near_C_stack_top (void)
203 return backtrace_args (backtrace_top ());
206 void
207 init_eval_once (void)
209 enum { size = 50 };
210 union specbinding *pdlvec = xmalloc ((size + 1) * sizeof *specpdl);
211 specpdl_size = size;
212 specpdl = specpdl_ptr = pdlvec + 1;
213 /* Don't forget to update docs (lispref node "Local Variables"). */
214 max_specpdl_size = 1300; /* 1000 is not enough for CEDET's c-by.el. */
215 max_lisp_eval_depth = 800;
217 Vrun_hooks = Qnil;
220 static struct handler handlerlist_sentinel;
222 void
223 init_eval (void)
225 byte_stack_list = 0;
226 specpdl_ptr = specpdl;
227 { /* Put a dummy catcher at top-level so that handlerlist is never NULL.
228 This is important since handlerlist->nextfree holds the freelist
229 which would otherwise leak every time we unwind back to top-level. */
230 handlerlist = handlerlist_sentinel.nextfree = &handlerlist_sentinel;
231 struct handler *c = push_handler (Qunbound, CATCHER);
232 eassert (c == &handlerlist_sentinel);
233 handlerlist_sentinel.nextfree = NULL;
234 handlerlist_sentinel.next = NULL;
236 Vquit_flag = Qnil;
237 debug_on_next_call = 0;
238 lisp_eval_depth = 0;
239 /* This is less than the initial value of num_nonmacro_input_events. */
240 when_entered_debugger = -1;
243 /* Unwind-protect function used by call_debugger. */
245 static void
246 restore_stack_limits (Lisp_Object data)
248 max_specpdl_size = XINT (XCAR (data));
249 max_lisp_eval_depth = XINT (XCDR (data));
252 static void grow_specpdl (void);
254 /* Call the Lisp debugger, giving it argument ARG. */
256 Lisp_Object
257 call_debugger (Lisp_Object arg)
259 bool debug_while_redisplaying;
260 ptrdiff_t count = SPECPDL_INDEX ();
261 Lisp_Object val;
262 EMACS_INT old_depth = max_lisp_eval_depth;
263 /* Do not allow max_specpdl_size less than actual depth (Bug#16603). */
264 EMACS_INT old_max = max (max_specpdl_size, count);
266 if (lisp_eval_depth + 40 > max_lisp_eval_depth)
267 max_lisp_eval_depth = lisp_eval_depth + 40;
269 /* While debugging Bug#16603, previous value of 100 was found
270 too small to avoid specpdl overflow in the debugger itself. */
271 if (max_specpdl_size - 200 < count)
272 max_specpdl_size = count + 200;
274 if (old_max == count)
276 /* We can enter the debugger due to specpdl overflow (Bug#16603). */
277 specpdl_ptr--;
278 grow_specpdl ();
281 /* Restore limits after leaving the debugger. */
282 record_unwind_protect (restore_stack_limits,
283 Fcons (make_number (old_max),
284 make_number (old_depth)));
286 #ifdef HAVE_WINDOW_SYSTEM
287 if (display_hourglass_p)
288 cancel_hourglass ();
289 #endif
291 debug_on_next_call = 0;
292 when_entered_debugger = num_nonmacro_input_events;
294 /* Resetting redisplaying_p to 0 makes sure that debug output is
295 displayed if the debugger is invoked during redisplay. */
296 debug_while_redisplaying = redisplaying_p;
297 redisplaying_p = 0;
298 specbind (intern ("debugger-may-continue"),
299 debug_while_redisplaying ? Qnil : Qt);
300 specbind (Qinhibit_redisplay, Qnil);
301 specbind (Qinhibit_debugger, Qt);
303 /* If we are debugging an error while `inhibit-changing-match-data'
304 is bound to non-nil (e.g., within a call to `string-match-p'),
305 then make sure debugger code can still use match data. */
306 specbind (Qinhibit_changing_match_data, Qnil);
308 #if 0 /* Binding this prevents execution of Lisp code during
309 redisplay, which necessarily leads to display problems. */
310 specbind (Qinhibit_eval_during_redisplay, Qt);
311 #endif
313 val = apply1 (Vdebugger, arg);
315 /* Interrupting redisplay and resuming it later is not safe under
316 all circumstances. So, when the debugger returns, abort the
317 interrupted redisplay by going back to the top-level. */
318 if (debug_while_redisplaying)
319 Ftop_level ();
321 return unbind_to (count, val);
324 static void
325 do_debug_on_call (Lisp_Object code, ptrdiff_t count)
327 debug_on_next_call = 0;
328 set_backtrace_debug_on_exit (specpdl + count, true);
329 call_debugger (list1 (code));
332 /* NOTE!!! Every function that can call EVAL must protect its args
333 and temporaries from garbage collection while it needs them.
334 The definition of `For' shows what you have to do. */
336 DEFUN ("or", For, Sor, 0, UNEVALLED, 0,
337 doc: /* Eval args until one of them yields non-nil, then return that value.
338 The remaining args are not evalled at all.
339 If all args return nil, return nil.
340 usage: (or CONDITIONS...) */)
341 (Lisp_Object args)
343 Lisp_Object val = Qnil;
345 while (CONSP (args))
347 val = eval_sub (XCAR (args));
348 if (!NILP (val))
349 break;
350 args = XCDR (args);
353 return val;
356 DEFUN ("and", Fand, Sand, 0, UNEVALLED, 0,
357 doc: /* Eval args until one of them yields nil, then return nil.
358 The remaining args are not evalled at all.
359 If no arg yields nil, return the last arg's value.
360 usage: (and CONDITIONS...) */)
361 (Lisp_Object args)
363 Lisp_Object val = Qt;
365 while (CONSP (args))
367 val = eval_sub (XCAR (args));
368 if (NILP (val))
369 break;
370 args = XCDR (args);
373 return val;
376 DEFUN ("if", Fif, Sif, 2, UNEVALLED, 0,
377 doc: /* If COND yields non-nil, do THEN, else do ELSE...
378 Returns the value of THEN or the value of the last of the ELSE's.
379 THEN must be one expression, but ELSE... can be zero or more expressions.
380 If COND yields nil, and there are no ELSE's, the value is nil.
381 usage: (if COND THEN ELSE...) */)
382 (Lisp_Object args)
384 Lisp_Object cond;
386 cond = eval_sub (XCAR (args));
388 if (!NILP (cond))
389 return eval_sub (Fcar (XCDR (args)));
390 return Fprogn (XCDR (XCDR (args)));
393 DEFUN ("cond", Fcond, Scond, 0, UNEVALLED, 0,
394 doc: /* Try each clause until one succeeds.
395 Each clause looks like (CONDITION BODY...). CONDITION is evaluated
396 and, if the value is non-nil, this clause succeeds:
397 then the expressions in BODY are evaluated and the last one's
398 value is the value of the cond-form.
399 If a clause has one element, as in (CONDITION), then the cond-form
400 returns CONDITION's value, if that is non-nil.
401 If no clause succeeds, cond returns nil.
402 usage: (cond CLAUSES...) */)
403 (Lisp_Object args)
405 Lisp_Object val = args;
407 while (CONSP (args))
409 Lisp_Object clause = XCAR (args);
410 val = eval_sub (Fcar (clause));
411 if (!NILP (val))
413 if (!NILP (XCDR (clause)))
414 val = Fprogn (XCDR (clause));
415 break;
417 args = XCDR (args);
420 return val;
423 DEFUN ("progn", Fprogn, Sprogn, 0, UNEVALLED, 0,
424 doc: /* Eval BODY forms sequentially and return value of last one.
425 usage: (progn BODY...) */)
426 (Lisp_Object body)
428 Lisp_Object val = Qnil;
430 while (CONSP (body))
432 val = eval_sub (XCAR (body));
433 body = XCDR (body);
436 return val;
439 /* Evaluate BODY sequentially, discarding its value. Suitable for
440 record_unwind_protect. */
442 void
443 unwind_body (Lisp_Object body)
445 Fprogn (body);
448 DEFUN ("prog1", Fprog1, Sprog1, 1, UNEVALLED, 0,
449 doc: /* Eval FIRST and BODY sequentially; return value from FIRST.
450 The value of FIRST is saved during the evaluation of the remaining args,
451 whose values are discarded.
452 usage: (prog1 FIRST BODY...) */)
453 (Lisp_Object args)
455 Lisp_Object val;
456 Lisp_Object args_left;
458 args_left = args;
459 val = args;
461 val = eval_sub (XCAR (args_left));
462 while (CONSP (args_left = XCDR (args_left)))
463 eval_sub (XCAR (args_left));
465 return val;
468 DEFUN ("prog2", Fprog2, Sprog2, 2, UNEVALLED, 0,
469 doc: /* Eval FORM1, FORM2 and BODY sequentially; return value from FORM2.
470 The value of FORM2 is saved during the evaluation of the
471 remaining args, whose values are discarded.
472 usage: (prog2 FORM1 FORM2 BODY...) */)
473 (Lisp_Object args)
475 eval_sub (XCAR (args));
476 return Fprog1 (XCDR (args));
479 DEFUN ("setq", Fsetq, Ssetq, 0, UNEVALLED, 0,
480 doc: /* Set each SYM to the value of its VAL.
481 The symbols SYM are variables; they are literal (not evaluated).
482 The values VAL are expressions; they are evaluated.
483 Thus, (setq x (1+ y)) sets `x' to the value of `(1+ y)'.
484 The second VAL is not computed until after the first SYM is set, and so on;
485 each VAL can use the new value of variables set earlier in the `setq'.
486 The return value of the `setq' form is the value of the last VAL.
487 usage: (setq [SYM VAL]...) */)
488 (Lisp_Object args)
490 Lisp_Object val, sym, lex_binding;
492 val = args;
493 if (CONSP (args))
495 Lisp_Object args_left = args;
496 Lisp_Object numargs = Flength (args);
498 if (XINT (numargs) & 1)
499 xsignal2 (Qwrong_number_of_arguments, Qsetq, numargs);
503 val = eval_sub (Fcar (XCDR (args_left)));
504 sym = XCAR (args_left);
506 /* Like for eval_sub, we do not check declared_special here since
507 it's been done when let-binding. */
508 if (!NILP (Vinternal_interpreter_environment) /* Mere optimization! */
509 && SYMBOLP (sym)
510 && !NILP (lex_binding
511 = Fassq (sym, Vinternal_interpreter_environment)))
512 XSETCDR (lex_binding, val); /* SYM is lexically bound. */
513 else
514 Fset (sym, val); /* SYM is dynamically bound. */
516 args_left = Fcdr (XCDR (args_left));
518 while (CONSP (args_left));
521 return val;
524 DEFUN ("quote", Fquote, Squote, 1, UNEVALLED, 0,
525 doc: /* Return the argument, without evaluating it. `(quote x)' yields `x'.
526 Warning: `quote' does not construct its return value, but just returns
527 the value that was pre-constructed by the Lisp reader (see info node
528 `(elisp)Printed Representation').
529 This means that \\='(a . b) is not identical to (cons \\='a \\='b): the former
530 does not cons. Quoting should be reserved for constants that will
531 never be modified by side-effects, unless you like self-modifying code.
532 See the common pitfall in info node `(elisp)Rearrangement' for an example
533 of unexpected results when a quoted object is modified.
534 usage: (quote ARG) */)
535 (Lisp_Object args)
537 if (CONSP (XCDR (args)))
538 xsignal2 (Qwrong_number_of_arguments, Qquote, Flength (args));
539 return XCAR (args);
542 DEFUN ("function", Ffunction, Sfunction, 1, UNEVALLED, 0,
543 doc: /* Like `quote', but preferred for objects which are functions.
544 In byte compilation, `function' causes its argument to be compiled.
545 `quote' cannot do that.
546 usage: (function ARG) */)
547 (Lisp_Object args)
549 Lisp_Object quoted = XCAR (args);
551 if (CONSP (XCDR (args)))
552 xsignal2 (Qwrong_number_of_arguments, Qfunction, Flength (args));
554 if (!NILP (Vinternal_interpreter_environment)
555 && CONSP (quoted)
556 && EQ (XCAR (quoted), Qlambda))
557 { /* This is a lambda expression within a lexical environment;
558 return an interpreted closure instead of a simple lambda. */
559 Lisp_Object cdr = XCDR (quoted);
560 Lisp_Object tmp = cdr;
561 if (CONSP (tmp)
562 && (tmp = XCDR (tmp), CONSP (tmp))
563 && (tmp = XCAR (tmp), CONSP (tmp))
564 && (EQ (QCdocumentation, XCAR (tmp))))
565 { /* Handle the special (:documentation <form>) to build the docstring
566 dynamically. */
567 Lisp_Object docstring = eval_sub (Fcar (XCDR (tmp)));
568 CHECK_STRING (docstring);
569 cdr = Fcons (XCAR (cdr), Fcons (docstring, XCDR (XCDR (cdr))));
571 return Fcons (Qclosure, Fcons (Vinternal_interpreter_environment,
572 cdr));
574 else
575 /* Simply quote the argument. */
576 return quoted;
580 DEFUN ("defvaralias", Fdefvaralias, Sdefvaralias, 2, 3, 0,
581 doc: /* Make NEW-ALIAS a variable alias for symbol BASE-VARIABLE.
582 Aliased variables always have the same value; setting one sets the other.
583 Third arg DOCSTRING, if non-nil, is documentation for NEW-ALIAS. If it is
584 omitted or nil, NEW-ALIAS gets the documentation string of BASE-VARIABLE,
585 or of the variable at the end of the chain of aliases, if BASE-VARIABLE is
586 itself an alias. If NEW-ALIAS is bound, and BASE-VARIABLE is not,
587 then the value of BASE-VARIABLE is set to that of NEW-ALIAS.
588 The return value is BASE-VARIABLE. */)
589 (Lisp_Object new_alias, Lisp_Object base_variable, Lisp_Object docstring)
591 struct Lisp_Symbol *sym;
593 CHECK_SYMBOL (new_alias);
594 CHECK_SYMBOL (base_variable);
596 sym = XSYMBOL (new_alias);
598 if (sym->constant)
599 /* Not sure why, but why not? */
600 error ("Cannot make a constant an alias");
602 switch (sym->redirect)
604 case SYMBOL_FORWARDED:
605 error ("Cannot make an internal variable an alias");
606 case SYMBOL_LOCALIZED:
607 error ("Don't know how to make a localized variable an alias");
608 case SYMBOL_PLAINVAL:
609 case SYMBOL_VARALIAS:
610 break;
611 default:
612 emacs_abort ();
615 /* http://lists.gnu.org/archive/html/emacs-devel/2008-04/msg00834.html
616 If n_a is bound, but b_v is not, set the value of b_v to n_a,
617 so that old-code that affects n_a before the aliasing is setup
618 still works. */
619 if (NILP (Fboundp (base_variable)))
620 set_internal (base_variable, find_symbol_value (new_alias), Qnil, 1);
623 union specbinding *p;
625 for (p = specpdl_ptr; p > specpdl; )
626 if ((--p)->kind >= SPECPDL_LET
627 && (EQ (new_alias, specpdl_symbol (p))))
628 error ("Don't know how to make a let-bound variable an alias");
631 sym->declared_special = 1;
632 XSYMBOL (base_variable)->declared_special = 1;
633 sym->redirect = SYMBOL_VARALIAS;
634 SET_SYMBOL_ALIAS (sym, XSYMBOL (base_variable));
635 sym->constant = SYMBOL_CONSTANT_P (base_variable);
636 LOADHIST_ATTACH (new_alias);
637 /* Even if docstring is nil: remove old docstring. */
638 Fput (new_alias, Qvariable_documentation, docstring);
640 return base_variable;
643 static union specbinding *
644 default_toplevel_binding (Lisp_Object symbol)
646 union specbinding *binding = NULL;
647 union specbinding *pdl = specpdl_ptr;
648 while (pdl > specpdl)
650 switch ((--pdl)->kind)
652 case SPECPDL_LET_DEFAULT:
653 case SPECPDL_LET:
654 if (EQ (specpdl_symbol (pdl), symbol))
655 binding = pdl;
656 break;
658 case SPECPDL_UNWIND:
659 case SPECPDL_UNWIND_PTR:
660 case SPECPDL_UNWIND_INT:
661 case SPECPDL_UNWIND_VOID:
662 case SPECPDL_BACKTRACE:
663 case SPECPDL_LET_LOCAL:
664 break;
666 default:
667 emacs_abort ();
670 return binding;
673 DEFUN ("default-toplevel-value", Fdefault_toplevel_value, Sdefault_toplevel_value, 1, 1, 0,
674 doc: /* Return SYMBOL's toplevel default value.
675 "Toplevel" means outside of any let binding. */)
676 (Lisp_Object symbol)
678 union specbinding *binding = default_toplevel_binding (symbol);
679 Lisp_Object value
680 = binding ? specpdl_old_value (binding) : Fdefault_value (symbol);
681 if (!EQ (value, Qunbound))
682 return value;
683 xsignal1 (Qvoid_variable, symbol);
686 DEFUN ("set-default-toplevel-value", Fset_default_toplevel_value,
687 Sset_default_toplevel_value, 2, 2, 0,
688 doc: /* Set SYMBOL's toplevel default value to VALUE.
689 "Toplevel" means outside of any let binding. */)
690 (Lisp_Object symbol, Lisp_Object value)
692 union specbinding *binding = default_toplevel_binding (symbol);
693 if (binding)
694 set_specpdl_old_value (binding, value);
695 else
696 Fset_default (symbol, value);
697 return Qnil;
700 DEFUN ("defvar", Fdefvar, Sdefvar, 1, UNEVALLED, 0,
701 doc: /* Define SYMBOL as a variable, and return SYMBOL.
702 You are not required to define a variable in order to use it, but
703 defining it lets you supply an initial value and documentation, which
704 can be referred to by the Emacs help facilities and other programming
705 tools. The `defvar' form also declares the variable as \"special\",
706 so that it is always dynamically bound even if `lexical-binding' is t.
708 The optional argument INITVALUE is evaluated, and used to set SYMBOL,
709 only if SYMBOL's value is void. If SYMBOL is buffer-local, its
710 default value is what is set; buffer-local values are not affected.
711 If INITVALUE is missing, SYMBOL's value is not set.
713 If SYMBOL has a local binding, then this form affects the local
714 binding. This is usually not what you want. Thus, if you need to
715 load a file defining variables, with this form or with `defconst' or
716 `defcustom', you should always load that file _outside_ any bindings
717 for these variables. (`defconst' and `defcustom' behave similarly in
718 this respect.)
720 The optional argument DOCSTRING is a documentation string for the
721 variable.
723 To define a user option, use `defcustom' instead of `defvar'.
724 usage: (defvar SYMBOL &optional INITVALUE DOCSTRING) */)
725 (Lisp_Object args)
727 Lisp_Object sym, tem, tail;
729 sym = XCAR (args);
730 tail = XCDR (args);
732 if (CONSP (tail))
734 if (CONSP (XCDR (tail)) && CONSP (XCDR (XCDR (tail))))
735 error ("Too many arguments");
737 tem = Fdefault_boundp (sym);
739 /* Do it before evaluating the initial value, for self-references. */
740 XSYMBOL (sym)->declared_special = 1;
742 if (NILP (tem))
743 Fset_default (sym, eval_sub (XCAR (tail)));
744 else
745 { /* Check if there is really a global binding rather than just a let
746 binding that shadows the global unboundness of the var. */
747 union specbinding *binding = default_toplevel_binding (sym);
748 if (binding && EQ (specpdl_old_value (binding), Qunbound))
750 set_specpdl_old_value (binding, eval_sub (XCAR (tail)));
753 tail = XCDR (tail);
754 tem = Fcar (tail);
755 if (!NILP (tem))
757 if (!NILP (Vpurify_flag))
758 tem = Fpurecopy (tem);
759 Fput (sym, Qvariable_documentation, tem);
761 LOADHIST_ATTACH (sym);
763 else if (!NILP (Vinternal_interpreter_environment)
764 && !XSYMBOL (sym)->declared_special)
765 /* A simple (defvar foo) with lexical scoping does "nothing" except
766 declare that var to be dynamically scoped *locally* (i.e. within
767 the current file or let-block). */
768 Vinternal_interpreter_environment
769 = Fcons (sym, Vinternal_interpreter_environment);
770 else
772 /* Simple (defvar <var>) should not count as a definition at all.
773 It could get in the way of other definitions, and unloading this
774 package could try to make the variable unbound. */
777 return sym;
780 DEFUN ("defconst", Fdefconst, Sdefconst, 2, UNEVALLED, 0,
781 doc: /* Define SYMBOL as a constant variable.
782 This declares that neither programs nor users should ever change the
783 value. This constancy is not actually enforced by Emacs Lisp, but
784 SYMBOL is marked as a special variable so that it is never lexically
785 bound.
787 The `defconst' form always sets the value of SYMBOL to the result of
788 evalling INITVALUE. If SYMBOL is buffer-local, its default value is
789 what is set; buffer-local values are not affected. If SYMBOL has a
790 local binding, then this form sets the local binding's value.
791 However, you should normally not make local bindings for variables
792 defined with this form.
794 The optional DOCSTRING specifies the variable's documentation string.
795 usage: (defconst SYMBOL INITVALUE [DOCSTRING]) */)
796 (Lisp_Object args)
798 Lisp_Object sym, tem;
800 sym = XCAR (args);
801 if (CONSP (Fcdr (XCDR (XCDR (args)))))
802 error ("Too many arguments");
804 tem = eval_sub (Fcar (XCDR (args)));
805 if (!NILP (Vpurify_flag))
806 tem = Fpurecopy (tem);
807 Fset_default (sym, tem);
808 XSYMBOL (sym)->declared_special = 1;
809 tem = Fcar (XCDR (XCDR (args)));
810 if (!NILP (tem))
812 if (!NILP (Vpurify_flag))
813 tem = Fpurecopy (tem);
814 Fput (sym, Qvariable_documentation, tem);
816 Fput (sym, Qrisky_local_variable, Qt);
817 LOADHIST_ATTACH (sym);
818 return sym;
821 /* Make SYMBOL lexically scoped. */
822 DEFUN ("internal-make-var-non-special", Fmake_var_non_special,
823 Smake_var_non_special, 1, 1, 0,
824 doc: /* Internal function. */)
825 (Lisp_Object symbol)
827 CHECK_SYMBOL (symbol);
828 XSYMBOL (symbol)->declared_special = 0;
829 return Qnil;
833 DEFUN ("let*", FletX, SletX, 1, UNEVALLED, 0,
834 doc: /* Bind variables according to VARLIST then eval BODY.
835 The value of the last form in BODY is returned.
836 Each element of VARLIST is a symbol (which is bound to nil)
837 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
838 Each VALUEFORM can refer to the symbols already bound by this VARLIST.
839 usage: (let* VARLIST BODY...) */)
840 (Lisp_Object args)
842 Lisp_Object varlist, var, val, elt, lexenv;
843 ptrdiff_t count = SPECPDL_INDEX ();
845 lexenv = Vinternal_interpreter_environment;
847 varlist = XCAR (args);
848 while (CONSP (varlist))
850 QUIT;
852 elt = XCAR (varlist);
853 if (SYMBOLP (elt))
855 var = elt;
856 val = Qnil;
858 else if (! NILP (Fcdr (Fcdr (elt))))
859 signal_error ("`let' bindings can have only one value-form", elt);
860 else
862 var = Fcar (elt);
863 val = eval_sub (Fcar (Fcdr (elt)));
866 if (!NILP (lexenv) && SYMBOLP (var)
867 && !XSYMBOL (var)->declared_special
868 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
869 /* Lexically bind VAR by adding it to the interpreter's binding
870 alist. */
872 Lisp_Object newenv
873 = Fcons (Fcons (var, val), Vinternal_interpreter_environment);
874 if (EQ (Vinternal_interpreter_environment, lexenv))
875 /* Save the old lexical environment on the specpdl stack,
876 but only for the first lexical binding, since we'll never
877 need to revert to one of the intermediate ones. */
878 specbind (Qinternal_interpreter_environment, newenv);
879 else
880 Vinternal_interpreter_environment = newenv;
882 else
883 specbind (var, val);
885 varlist = XCDR (varlist);
888 val = Fprogn (XCDR (args));
889 return unbind_to (count, val);
892 DEFUN ("let", Flet, Slet, 1, UNEVALLED, 0,
893 doc: /* Bind variables according to VARLIST then eval BODY.
894 The value of the last form in BODY is returned.
895 Each element of VARLIST is a symbol (which is bound to nil)
896 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
897 All the VALUEFORMs are evalled before any symbols are bound.
898 usage: (let VARLIST BODY...) */)
899 (Lisp_Object args)
901 Lisp_Object *temps, tem, lexenv;
902 Lisp_Object elt, varlist;
903 ptrdiff_t count = SPECPDL_INDEX ();
904 ptrdiff_t argnum;
905 USE_SAFE_ALLOCA;
907 varlist = XCAR (args);
909 /* Make space to hold the values to give the bound variables. */
910 elt = Flength (varlist);
911 SAFE_ALLOCA_LISP (temps, XFASTINT (elt));
913 /* Compute the values and store them in `temps'. */
915 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
917 QUIT;
918 elt = XCAR (varlist);
919 if (SYMBOLP (elt))
920 temps [argnum++] = Qnil;
921 else if (! NILP (Fcdr (Fcdr (elt))))
922 signal_error ("`let' bindings can have only one value-form", elt);
923 else
924 temps [argnum++] = eval_sub (Fcar (Fcdr (elt)));
927 lexenv = Vinternal_interpreter_environment;
929 varlist = XCAR (args);
930 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
932 Lisp_Object var;
934 elt = XCAR (varlist);
935 var = SYMBOLP (elt) ? elt : Fcar (elt);
936 tem = temps[argnum++];
938 if (!NILP (lexenv) && SYMBOLP (var)
939 && !XSYMBOL (var)->declared_special
940 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
941 /* Lexically bind VAR by adding it to the lexenv alist. */
942 lexenv = Fcons (Fcons (var, tem), lexenv);
943 else
944 /* Dynamically bind VAR. */
945 specbind (var, tem);
948 if (!EQ (lexenv, Vinternal_interpreter_environment))
949 /* Instantiate a new lexical environment. */
950 specbind (Qinternal_interpreter_environment, lexenv);
952 elt = Fprogn (XCDR (args));
953 SAFE_FREE ();
954 return unbind_to (count, elt);
957 DEFUN ("while", Fwhile, Swhile, 1, UNEVALLED, 0,
958 doc: /* If TEST yields non-nil, eval BODY... and repeat.
959 The order of execution is thus TEST, BODY, TEST, BODY and so on
960 until TEST returns nil.
961 usage: (while TEST BODY...) */)
962 (Lisp_Object args)
964 Lisp_Object test, body;
966 test = XCAR (args);
967 body = XCDR (args);
968 while (!NILP (eval_sub (test)))
970 QUIT;
971 Fprogn (body);
974 return Qnil;
977 DEFUN ("macroexpand", Fmacroexpand, Smacroexpand, 1, 2, 0,
978 doc: /* Return result of expanding macros at top level of FORM.
979 If FORM is not a macro call, it is returned unchanged.
980 Otherwise, the macro is expanded and the expansion is considered
981 in place of FORM. When a non-macro-call results, it is returned.
983 The second optional arg ENVIRONMENT specifies an environment of macro
984 definitions to shadow the loaded ones for use in file byte-compilation. */)
985 (Lisp_Object form, Lisp_Object environment)
987 /* With cleanups from Hallvard Furuseth. */
988 register Lisp_Object expander, sym, def, tem;
990 while (1)
992 /* Come back here each time we expand a macro call,
993 in case it expands into another macro call. */
994 if (!CONSP (form))
995 break;
996 /* Set SYM, give DEF and TEM right values in case SYM is not a symbol. */
997 def = sym = XCAR (form);
998 tem = Qnil;
999 /* Trace symbols aliases to other symbols
1000 until we get a symbol that is not an alias. */
1001 while (SYMBOLP (def))
1003 QUIT;
1004 sym = def;
1005 tem = Fassq (sym, environment);
1006 if (NILP (tem))
1008 def = XSYMBOL (sym)->function;
1009 if (!NILP (def))
1010 continue;
1012 break;
1014 /* Right now TEM is the result from SYM in ENVIRONMENT,
1015 and if TEM is nil then DEF is SYM's function definition. */
1016 if (NILP (tem))
1018 /* SYM is not mentioned in ENVIRONMENT.
1019 Look at its function definition. */
1020 def = Fautoload_do_load (def, sym, Qmacro);
1021 if (!CONSP (def))
1022 /* Not defined or definition not suitable. */
1023 break;
1024 if (!EQ (XCAR (def), Qmacro))
1025 break;
1026 else expander = XCDR (def);
1028 else
1030 expander = XCDR (tem);
1031 if (NILP (expander))
1032 break;
1035 Lisp_Object newform = apply1 (expander, XCDR (form));
1036 if (EQ (form, newform))
1037 break;
1038 else
1039 form = newform;
1042 return form;
1045 DEFUN ("catch", Fcatch, Scatch, 1, UNEVALLED, 0,
1046 doc: /* Eval BODY allowing nonlocal exits using `throw'.
1047 TAG is evalled to get the tag to use; it must not be nil.
1049 Then the BODY is executed.
1050 Within BODY, a call to `throw' with the same TAG exits BODY and this `catch'.
1051 If no throw happens, `catch' returns the value of the last BODY form.
1052 If a throw happens, it specifies the value to return from `catch'.
1053 usage: (catch TAG BODY...) */)
1054 (Lisp_Object args)
1056 Lisp_Object tag = eval_sub (XCAR (args));
1057 return internal_catch (tag, Fprogn, XCDR (args));
1060 /* Assert that E is true, as a comment only. Use this instead of
1061 eassert (E) when E contains variables that might be clobbered by a
1062 longjmp. */
1064 #define clobbered_eassert(E) ((void) 0)
1066 /* Set up a catch, then call C function FUNC on argument ARG.
1067 FUNC should return a Lisp_Object.
1068 This is how catches are done from within C code. */
1070 Lisp_Object
1071 internal_catch (Lisp_Object tag,
1072 Lisp_Object (*func) (Lisp_Object), Lisp_Object arg)
1074 /* This structure is made part of the chain `catchlist'. */
1075 struct handler *c = push_handler (tag, CATCHER);
1077 /* Call FUNC. */
1078 if (! sys_setjmp (c->jmp))
1080 Lisp_Object val = func (arg);
1081 clobbered_eassert (handlerlist == c);
1082 handlerlist = handlerlist->next;
1083 return val;
1085 else
1086 { /* Throw works by a longjmp that comes right here. */
1087 Lisp_Object val = handlerlist->val;
1088 clobbered_eassert (handlerlist == c);
1089 handlerlist = handlerlist->next;
1090 return val;
1094 /* Unwind the specbind, catch, and handler stacks back to CATCH, and
1095 jump to that CATCH, returning VALUE as the value of that catch.
1097 This is the guts of Fthrow and Fsignal; they differ only in the way
1098 they choose the catch tag to throw to. A catch tag for a
1099 condition-case form has a TAG of Qnil.
1101 Before each catch is discarded, unbind all special bindings and
1102 execute all unwind-protect clauses made above that catch. Unwind
1103 the handler stack as we go, so that the proper handlers are in
1104 effect for each unwind-protect clause we run. At the end, restore
1105 some static info saved in CATCH, and longjmp to the location
1106 specified there.
1108 This is used for correct unwinding in Fthrow and Fsignal. */
1110 static _Noreturn void
1111 unwind_to_catch (struct handler *catch, Lisp_Object value)
1113 bool last_time;
1115 eassert (catch->next);
1117 /* Save the value in the tag. */
1118 catch->val = value;
1120 /* Restore certain special C variables. */
1121 set_poll_suppress_count (catch->poll_suppress_count);
1122 unblock_input_to (catch->interrupt_input_blocked);
1123 immediate_quit = 0;
1127 /* Unwind the specpdl stack, and then restore the proper set of
1128 handlers. */
1129 unbind_to (handlerlist->pdlcount, Qnil);
1130 last_time = handlerlist == catch;
1131 if (! last_time)
1132 handlerlist = handlerlist->next;
1134 while (! last_time);
1136 eassert (handlerlist == catch);
1138 byte_stack_list = catch->byte_stack;
1139 lisp_eval_depth = catch->lisp_eval_depth;
1141 sys_longjmp (catch->jmp, 1);
1144 DEFUN ("throw", Fthrow, Sthrow, 2, 2, 0,
1145 doc: /* Throw to the catch for TAG and return VALUE from it.
1146 Both TAG and VALUE are evalled. */
1147 attributes: noreturn)
1148 (register Lisp_Object tag, Lisp_Object value)
1150 struct handler *c;
1152 if (!NILP (tag))
1153 for (c = handlerlist; c; c = c->next)
1155 if (c->type == CATCHER_ALL)
1156 unwind_to_catch (c, Fcons (tag, value));
1157 if (c->type == CATCHER && EQ (c->tag_or_ch, tag))
1158 unwind_to_catch (c, value);
1160 xsignal2 (Qno_catch, tag, value);
1164 DEFUN ("unwind-protect", Funwind_protect, Sunwind_protect, 1, UNEVALLED, 0,
1165 doc: /* Do BODYFORM, protecting with UNWINDFORMS.
1166 If BODYFORM completes normally, its value is returned
1167 after executing the UNWINDFORMS.
1168 If BODYFORM exits nonlocally, the UNWINDFORMS are executed anyway.
1169 usage: (unwind-protect BODYFORM UNWINDFORMS...) */)
1170 (Lisp_Object args)
1172 Lisp_Object val;
1173 ptrdiff_t count = SPECPDL_INDEX ();
1175 record_unwind_protect (unwind_body, XCDR (args));
1176 val = eval_sub (XCAR (args));
1177 return unbind_to (count, val);
1180 DEFUN ("condition-case", Fcondition_case, Scondition_case, 2, UNEVALLED, 0,
1181 doc: /* Regain control when an error is signaled.
1182 Executes BODYFORM and returns its value if no error happens.
1183 Each element of HANDLERS looks like (CONDITION-NAME BODY...)
1184 where the BODY is made of Lisp expressions.
1186 A handler is applicable to an error
1187 if CONDITION-NAME is one of the error's condition names.
1188 If an error happens, the first applicable handler is run.
1190 The car of a handler may be a list of condition names instead of a
1191 single condition name; then it handles all of them. If the special
1192 condition name `debug' is present in this list, it allows another
1193 condition in the list to run the debugger if `debug-on-error' and the
1194 other usual mechanisms says it should (otherwise, `condition-case'
1195 suppresses the debugger).
1197 When a handler handles an error, control returns to the `condition-case'
1198 and it executes the handler's BODY...
1199 with VAR bound to (ERROR-SYMBOL . SIGNAL-DATA) from the error.
1200 \(If VAR is nil, the handler can't access that information.)
1201 Then the value of the last BODY form is returned from the `condition-case'
1202 expression.
1204 See also the function `signal' for more info.
1205 usage: (condition-case VAR BODYFORM &rest HANDLERS) */)
1206 (Lisp_Object args)
1208 Lisp_Object var = XCAR (args);
1209 Lisp_Object bodyform = XCAR (XCDR (args));
1210 Lisp_Object handlers = XCDR (XCDR (args));
1212 return internal_lisp_condition_case (var, bodyform, handlers);
1215 /* Like Fcondition_case, but the args are separate
1216 rather than passed in a list. Used by Fbyte_code. */
1218 Lisp_Object
1219 internal_lisp_condition_case (volatile Lisp_Object var, Lisp_Object bodyform,
1220 Lisp_Object handlers)
1222 Lisp_Object val;
1223 struct handler *oldhandlerlist = handlerlist;
1224 int clausenb = 0;
1226 CHECK_SYMBOL (var);
1228 for (val = handlers; CONSP (val); val = XCDR (val))
1230 Lisp_Object tem = XCAR (val);
1231 clausenb++;
1232 if (! (NILP (tem)
1233 || (CONSP (tem)
1234 && (SYMBOLP (XCAR (tem))
1235 || CONSP (XCAR (tem))))))
1236 error ("Invalid condition handler: %s",
1237 SDATA (Fprin1_to_string (tem, Qt)));
1240 { /* The first clause is the one that should be checked first, so it should
1241 be added to handlerlist last. So we build in `clauses' a table that
1242 contains `handlers' but in reverse order. SAFE_ALLOCA won't work
1243 here due to the setjmp, so impose a MAX_ALLOCA limit. */
1244 if (MAX_ALLOCA / word_size < clausenb)
1245 memory_full (SIZE_MAX);
1246 Lisp_Object *clauses = alloca (clausenb * sizeof *clauses);
1247 Lisp_Object *volatile clauses_volatile = clauses;
1248 int i = clausenb;
1249 for (val = handlers; CONSP (val); val = XCDR (val))
1250 clauses[--i] = XCAR (val);
1251 for (i = 0; i < clausenb; i++)
1253 Lisp_Object clause = clauses[i];
1254 Lisp_Object condition = CONSP (clause) ? XCAR (clause) : Qnil;
1255 if (!CONSP (condition))
1256 condition = Fcons (condition, Qnil);
1257 struct handler *c = push_handler (condition, CONDITION_CASE);
1258 if (sys_setjmp (c->jmp))
1260 ptrdiff_t count = SPECPDL_INDEX ();
1261 Lisp_Object val = handlerlist->val;
1262 Lisp_Object *chosen_clause = clauses_volatile;
1263 for (c = handlerlist->next; c != oldhandlerlist; c = c->next)
1264 chosen_clause++;
1265 handlerlist = oldhandlerlist;
1266 if (!NILP (var))
1268 if (!NILP (Vinternal_interpreter_environment))
1269 specbind (Qinternal_interpreter_environment,
1270 Fcons (Fcons (var, val),
1271 Vinternal_interpreter_environment));
1272 else
1273 specbind (var, val);
1275 val = Fprogn (XCDR (*chosen_clause));
1276 /* Note that this just undoes the binding of var; whoever
1277 longjumped to us unwound the stack to c.pdlcount before
1278 throwing. */
1279 if (!NILP (var))
1280 unbind_to (count, Qnil);
1281 return val;
1286 val = eval_sub (bodyform);
1287 handlerlist = oldhandlerlist;
1288 return val;
1291 /* Call the function BFUN with no arguments, catching errors within it
1292 according to HANDLERS. If there is an error, call HFUN with
1293 one argument which is the data that describes the error:
1294 (SIGNALNAME . DATA)
1296 HANDLERS can be a list of conditions to catch.
1297 If HANDLERS is Qt, catch all errors.
1298 If HANDLERS is Qerror, catch all errors
1299 but allow the debugger to run if that is enabled. */
1301 Lisp_Object
1302 internal_condition_case (Lisp_Object (*bfun) (void), Lisp_Object handlers,
1303 Lisp_Object (*hfun) (Lisp_Object))
1305 struct handler *c = push_handler (handlers, CONDITION_CASE);
1306 if (sys_setjmp (c->jmp))
1308 Lisp_Object val = handlerlist->val;
1309 clobbered_eassert (handlerlist == c);
1310 handlerlist = handlerlist->next;
1311 return hfun (val);
1313 else
1315 Lisp_Object val = bfun ();
1316 clobbered_eassert (handlerlist == c);
1317 handlerlist = handlerlist->next;
1318 return val;
1322 /* Like internal_condition_case but call BFUN with ARG as its argument. */
1324 Lisp_Object
1325 internal_condition_case_1 (Lisp_Object (*bfun) (Lisp_Object), Lisp_Object arg,
1326 Lisp_Object handlers,
1327 Lisp_Object (*hfun) (Lisp_Object))
1329 struct handler *c = push_handler (handlers, CONDITION_CASE);
1330 if (sys_setjmp (c->jmp))
1332 Lisp_Object val = handlerlist->val;
1333 clobbered_eassert (handlerlist == c);
1334 handlerlist = handlerlist->next;
1335 return hfun (val);
1337 else
1339 Lisp_Object val = bfun (arg);
1340 clobbered_eassert (handlerlist == c);
1341 handlerlist = handlerlist->next;
1342 return val;
1346 /* Like internal_condition_case_1 but call BFUN with ARG1 and ARG2 as
1347 its arguments. */
1349 Lisp_Object
1350 internal_condition_case_2 (Lisp_Object (*bfun) (Lisp_Object, Lisp_Object),
1351 Lisp_Object arg1,
1352 Lisp_Object arg2,
1353 Lisp_Object handlers,
1354 Lisp_Object (*hfun) (Lisp_Object))
1356 struct handler *c = push_handler (handlers, CONDITION_CASE);
1357 if (sys_setjmp (c->jmp))
1359 Lisp_Object val = handlerlist->val;
1360 clobbered_eassert (handlerlist == c);
1361 handlerlist = handlerlist->next;
1362 return hfun (val);
1364 else
1366 Lisp_Object val = bfun (arg1, arg2);
1367 clobbered_eassert (handlerlist == c);
1368 handlerlist = handlerlist->next;
1369 return val;
1373 /* Like internal_condition_case but call BFUN with NARGS as first,
1374 and ARGS as second argument. */
1376 Lisp_Object
1377 internal_condition_case_n (Lisp_Object (*bfun) (ptrdiff_t, Lisp_Object *),
1378 ptrdiff_t nargs,
1379 Lisp_Object *args,
1380 Lisp_Object handlers,
1381 Lisp_Object (*hfun) (Lisp_Object err,
1382 ptrdiff_t nargs,
1383 Lisp_Object *args))
1385 struct handler *c = push_handler (handlers, CONDITION_CASE);
1386 if (sys_setjmp (c->jmp))
1388 Lisp_Object val = handlerlist->val;
1389 clobbered_eassert (handlerlist == c);
1390 handlerlist = handlerlist->next;
1391 return hfun (val, nargs, args);
1393 else
1395 Lisp_Object val = bfun (nargs, args);
1396 clobbered_eassert (handlerlist == c);
1397 handlerlist = handlerlist->next;
1398 return val;
1402 struct handler *
1403 push_handler (Lisp_Object tag_ch_val, enum handlertype handlertype)
1405 struct handler *c = push_handler_nosignal (tag_ch_val, handlertype);
1406 if (!c)
1407 memory_full (sizeof *c);
1408 return c;
1411 struct handler *
1412 push_handler_nosignal (Lisp_Object tag_ch_val, enum handlertype handlertype)
1414 struct handler *c = handlerlist->nextfree;
1415 if (!c)
1417 c = malloc (sizeof *c);
1418 if (!c)
1419 return c;
1420 if (profiler_memory_running)
1421 malloc_probe (sizeof *c);
1422 c->nextfree = NULL;
1423 handlerlist->nextfree = c;
1425 c->type = handlertype;
1426 c->tag_or_ch = tag_ch_val;
1427 c->val = Qnil;
1428 c->next = handlerlist;
1429 c->lisp_eval_depth = lisp_eval_depth;
1430 c->pdlcount = SPECPDL_INDEX ();
1431 c->poll_suppress_count = poll_suppress_count;
1432 c->interrupt_input_blocked = interrupt_input_blocked;
1433 c->byte_stack = byte_stack_list;
1434 handlerlist = c;
1435 return c;
1439 static Lisp_Object signal_or_quit (Lisp_Object, Lisp_Object, bool);
1440 static Lisp_Object find_handler_clause (Lisp_Object, Lisp_Object);
1441 static bool maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig,
1442 Lisp_Object data);
1444 void
1445 process_quit_flag (void)
1447 Lisp_Object flag = Vquit_flag;
1448 Vquit_flag = Qnil;
1449 if (EQ (flag, Qkill_emacs))
1450 Fkill_emacs (Qnil);
1451 if (EQ (Vthrow_on_input, flag))
1452 Fthrow (Vthrow_on_input, Qt);
1453 quit ();
1456 DEFUN ("signal", Fsignal, Ssignal, 2, 2, 0,
1457 doc: /* Signal an error. Args are ERROR-SYMBOL and associated DATA.
1458 This function does not return.
1460 An error symbol is a symbol with an `error-conditions' property
1461 that is a list of condition names.
1462 A handler for any of those names will get to handle this signal.
1463 The symbol `error' should normally be one of them.
1465 DATA should be a list. Its elements are printed as part of the error message.
1466 See Info anchor `(elisp)Definition of signal' for some details on how this
1467 error message is constructed.
1468 If the signal is handled, DATA is made available to the handler.
1469 See also the function `condition-case'. */
1470 attributes: noreturn)
1471 (Lisp_Object error_symbol, Lisp_Object data)
1473 signal_or_quit (error_symbol, data, false);
1474 eassume (false);
1477 /* Quit, in response to a keyboard quit request. */
1478 Lisp_Object
1479 quit (void)
1481 return signal_or_quit (Qquit, Qnil, true);
1484 /* Signal an error, or quit. ERROR_SYMBOL and DATA are as with Fsignal.
1485 If KEYBOARD_QUIT, this is a quit; ERROR_SYMBOL should be
1486 Qquit and DATA should be Qnil, and this function may return.
1487 Otherwise this function is like Fsignal and does not return. */
1489 static Lisp_Object
1490 signal_or_quit (Lisp_Object error_symbol, Lisp_Object data, bool keyboard_quit)
1492 /* When memory is full, ERROR-SYMBOL is nil,
1493 and DATA is (REAL-ERROR-SYMBOL . REAL-DATA).
1494 That is a special case--don't do this in other situations. */
1495 Lisp_Object conditions;
1496 Lisp_Object string;
1497 Lisp_Object real_error_symbol
1498 = (NILP (error_symbol) ? Fcar (data) : error_symbol);
1499 register Lisp_Object clause = Qnil;
1500 struct handler *h;
1502 immediate_quit = 0;
1503 abort_on_gc = 0;
1504 if (gc_in_progress || waiting_for_input)
1505 emacs_abort ();
1507 #if 0 /* rms: I don't know why this was here,
1508 but it is surely wrong for an error that is handled. */
1509 #ifdef HAVE_WINDOW_SYSTEM
1510 if (display_hourglass_p)
1511 cancel_hourglass ();
1512 #endif
1513 #endif
1515 /* This hook is used by edebug. */
1516 if (! NILP (Vsignal_hook_function)
1517 && ! NILP (error_symbol))
1519 /* Edebug takes care of restoring these variables when it exits. */
1520 if (lisp_eval_depth + 20 > max_lisp_eval_depth)
1521 max_lisp_eval_depth = lisp_eval_depth + 20;
1523 if (SPECPDL_INDEX () + 40 > max_specpdl_size)
1524 max_specpdl_size = SPECPDL_INDEX () + 40;
1526 call2 (Vsignal_hook_function, error_symbol, data);
1529 conditions = Fget (real_error_symbol, Qerror_conditions);
1531 /* Remember from where signal was called. Skip over the frame for
1532 `signal' itself. If a frame for `error' follows, skip that,
1533 too. Don't do this when ERROR_SYMBOL is nil, because that
1534 is a memory-full error. */
1535 Vsignaling_function = Qnil;
1536 if (!NILP (error_symbol))
1538 union specbinding *pdl = backtrace_next (backtrace_top ());
1539 if (backtrace_p (pdl) && EQ (backtrace_function (pdl), Qerror))
1540 pdl = backtrace_next (pdl);
1541 if (backtrace_p (pdl))
1542 Vsignaling_function = backtrace_function (pdl);
1545 for (h = handlerlist; h; h = h->next)
1547 if (h->type != CONDITION_CASE)
1548 continue;
1549 clause = find_handler_clause (h->tag_or_ch, conditions);
1550 if (!NILP (clause))
1551 break;
1554 if (/* Don't run the debugger for a memory-full error.
1555 (There is no room in memory to do that!) */
1556 !NILP (error_symbol)
1557 && (!NILP (Vdebug_on_signal)
1558 /* If no handler is present now, try to run the debugger. */
1559 || NILP (clause)
1560 /* A `debug' symbol in the handler list disables the normal
1561 suppression of the debugger. */
1562 || (CONSP (clause) && !NILP (Fmemq (Qdebug, clause)))
1563 /* Special handler that means "print a message and run debugger
1564 if requested". */
1565 || EQ (h->tag_or_ch, Qerror)))
1567 bool debugger_called
1568 = maybe_call_debugger (conditions, error_symbol, data);
1569 /* We can't return values to code which signaled an error, but we
1570 can continue code which has signaled a quit. */
1571 if (keyboard_quit && debugger_called && EQ (real_error_symbol, Qquit))
1572 return Qnil;
1575 if (!NILP (clause))
1577 Lisp_Object unwind_data
1578 = (NILP (error_symbol) ? data : Fcons (error_symbol, data));
1580 unwind_to_catch (h, unwind_data);
1582 else
1584 if (handlerlist != &handlerlist_sentinel)
1585 /* FIXME: This will come right back here if there's no `top-level'
1586 catcher. A better solution would be to abort here, and instead
1587 add a catch-all condition handler so we never come here. */
1588 Fthrow (Qtop_level, Qt);
1591 if (! NILP (error_symbol))
1592 data = Fcons (error_symbol, data);
1594 string = Ferror_message_string (data);
1595 fatal ("%s", SDATA (string));
1598 /* Like xsignal, but takes 0, 1, 2, or 3 args instead of a list. */
1600 void
1601 xsignal0 (Lisp_Object error_symbol)
1603 xsignal (error_symbol, Qnil);
1606 void
1607 xsignal1 (Lisp_Object error_symbol, Lisp_Object arg)
1609 xsignal (error_symbol, list1 (arg));
1612 void
1613 xsignal2 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2)
1615 xsignal (error_symbol, list2 (arg1, arg2));
1618 void
1619 xsignal3 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
1621 xsignal (error_symbol, list3 (arg1, arg2, arg3));
1624 /* Signal `error' with message S, and additional arg ARG.
1625 If ARG is not a genuine list, make it a one-element list. */
1627 void
1628 signal_error (const char *s, Lisp_Object arg)
1630 Lisp_Object tortoise, hare;
1632 hare = tortoise = arg;
1633 while (CONSP (hare))
1635 hare = XCDR (hare);
1636 if (!CONSP (hare))
1637 break;
1639 hare = XCDR (hare);
1640 tortoise = XCDR (tortoise);
1642 if (EQ (hare, tortoise))
1643 break;
1646 if (!NILP (hare))
1647 arg = list1 (arg);
1649 xsignal (Qerror, Fcons (build_string (s), arg));
1653 /* Return true if LIST is a non-nil atom or
1654 a list containing one of CONDITIONS. */
1656 static bool
1657 wants_debugger (Lisp_Object list, Lisp_Object conditions)
1659 if (NILP (list))
1660 return 0;
1661 if (! CONSP (list))
1662 return 1;
1664 while (CONSP (conditions))
1666 Lisp_Object this, tail;
1667 this = XCAR (conditions);
1668 for (tail = list; CONSP (tail); tail = XCDR (tail))
1669 if (EQ (XCAR (tail), this))
1670 return 1;
1671 conditions = XCDR (conditions);
1673 return 0;
1676 /* Return true if an error with condition-symbols CONDITIONS,
1677 and described by SIGNAL-DATA, should skip the debugger
1678 according to debugger-ignored-errors. */
1680 static bool
1681 skip_debugger (Lisp_Object conditions, Lisp_Object data)
1683 Lisp_Object tail;
1684 bool first_string = 1;
1685 Lisp_Object error_message;
1687 error_message = Qnil;
1688 for (tail = Vdebug_ignored_errors; CONSP (tail); tail = XCDR (tail))
1690 if (STRINGP (XCAR (tail)))
1692 if (first_string)
1694 error_message = Ferror_message_string (data);
1695 first_string = 0;
1698 if (fast_string_match (XCAR (tail), error_message) >= 0)
1699 return 1;
1701 else
1703 Lisp_Object contail;
1705 for (contail = conditions; CONSP (contail); contail = XCDR (contail))
1706 if (EQ (XCAR (tail), XCAR (contail)))
1707 return 1;
1711 return 0;
1714 /* Call the debugger if calling it is currently enabled for CONDITIONS.
1715 SIG and DATA describe the signal. There are two ways to pass them:
1716 = SIG is the error symbol, and DATA is the rest of the data.
1717 = SIG is nil, and DATA is (SYMBOL . REST-OF-DATA).
1718 This is for memory-full errors only. */
1719 static bool
1720 maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig, Lisp_Object data)
1722 Lisp_Object combined_data;
1724 combined_data = Fcons (sig, data);
1726 if (
1727 /* Don't try to run the debugger with interrupts blocked.
1728 The editing loop would return anyway. */
1729 ! input_blocked_p ()
1730 && NILP (Vinhibit_debugger)
1731 /* Does user want to enter debugger for this kind of error? */
1732 && (EQ (sig, Qquit)
1733 ? debug_on_quit
1734 : wants_debugger (Vdebug_on_error, conditions))
1735 && ! skip_debugger (conditions, combined_data)
1736 /* RMS: What's this for? */
1737 && when_entered_debugger < num_nonmacro_input_events)
1739 call_debugger (list2 (Qerror, combined_data));
1740 return 1;
1743 return 0;
1746 static Lisp_Object
1747 find_handler_clause (Lisp_Object handlers, Lisp_Object conditions)
1749 register Lisp_Object h;
1751 /* t is used by handlers for all conditions, set up by C code. */
1752 if (EQ (handlers, Qt))
1753 return Qt;
1755 /* error is used similarly, but means print an error message
1756 and run the debugger if that is enabled. */
1757 if (EQ (handlers, Qerror))
1758 return Qt;
1760 for (h = handlers; CONSP (h); h = XCDR (h))
1762 Lisp_Object handler = XCAR (h);
1763 if (!NILP (Fmemq (handler, conditions)))
1764 return handlers;
1767 return Qnil;
1771 /* Format and return a string; called like vprintf. */
1772 Lisp_Object
1773 vformat_string (const char *m, va_list ap)
1775 char buf[4000];
1776 ptrdiff_t size = sizeof buf;
1777 ptrdiff_t size_max = STRING_BYTES_BOUND + 1;
1778 char *buffer = buf;
1779 ptrdiff_t used;
1780 Lisp_Object string;
1782 used = evxprintf (&buffer, &size, buf, size_max, m, ap);
1783 string = make_string (buffer, used);
1784 if (buffer != buf)
1785 xfree (buffer);
1787 return string;
1790 /* Dump an error message; called like vprintf. */
1791 void
1792 verror (const char *m, va_list ap)
1794 xsignal1 (Qerror, vformat_string (m, ap));
1798 /* Dump an error message; called like printf. */
1800 /* VARARGS 1 */
1801 void
1802 error (const char *m, ...)
1804 va_list ap;
1805 va_start (ap, m);
1806 verror (m, ap);
1809 DEFUN ("commandp", Fcommandp, Scommandp, 1, 2, 0,
1810 doc: /* Non-nil if FUNCTION makes provisions for interactive calling.
1811 This means it contains a description for how to read arguments to give it.
1812 The value is nil for an invalid function or a symbol with no function
1813 definition.
1815 Interactively callable functions include strings and vectors (treated
1816 as keyboard macros), lambda-expressions that contain a top-level call
1817 to `interactive', autoload definitions made by `autoload' with non-nil
1818 fourth argument, and some of the built-in functions of Lisp.
1820 Also, a symbol satisfies `commandp' if its function definition does so.
1822 If the optional argument FOR-CALL-INTERACTIVELY is non-nil,
1823 then strings and vectors are not accepted. */)
1824 (Lisp_Object function, Lisp_Object for_call_interactively)
1826 register Lisp_Object fun;
1827 register Lisp_Object funcar;
1828 Lisp_Object if_prop = Qnil;
1830 fun = function;
1832 fun = indirect_function (fun); /* Check cycles. */
1833 if (NILP (fun))
1834 return Qnil;
1836 /* Check an `interactive-form' property if present, analogous to the
1837 function-documentation property. */
1838 fun = function;
1839 while (SYMBOLP (fun))
1841 Lisp_Object tmp = Fget (fun, Qinteractive_form);
1842 if (!NILP (tmp))
1843 if_prop = Qt;
1844 fun = Fsymbol_function (fun);
1847 /* Emacs primitives are interactive if their DEFUN specifies an
1848 interactive spec. */
1849 if (SUBRP (fun))
1850 return XSUBR (fun)->intspec ? Qt : if_prop;
1852 /* Bytecode objects are interactive if they are long enough to
1853 have an element whose index is COMPILED_INTERACTIVE, which is
1854 where the interactive spec is stored. */
1855 else if (COMPILEDP (fun))
1856 return ((ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK) > COMPILED_INTERACTIVE
1857 ? Qt : if_prop);
1859 /* Strings and vectors are keyboard macros. */
1860 if (STRINGP (fun) || VECTORP (fun))
1861 return (NILP (for_call_interactively) ? Qt : Qnil);
1863 /* Lists may represent commands. */
1864 if (!CONSP (fun))
1865 return Qnil;
1866 funcar = XCAR (fun);
1867 if (EQ (funcar, Qclosure))
1868 return (!NILP (Fassq (Qinteractive, Fcdr (Fcdr (XCDR (fun)))))
1869 ? Qt : if_prop);
1870 else if (EQ (funcar, Qlambda))
1871 return !NILP (Fassq (Qinteractive, Fcdr (XCDR (fun)))) ? Qt : if_prop;
1872 else if (EQ (funcar, Qautoload))
1873 return !NILP (Fcar (Fcdr (Fcdr (XCDR (fun))))) ? Qt : if_prop;
1874 else
1875 return Qnil;
1878 DEFUN ("autoload", Fautoload, Sautoload, 2, 5, 0,
1879 doc: /* Define FUNCTION to autoload from FILE.
1880 FUNCTION is a symbol; FILE is a file name string to pass to `load'.
1881 Third arg DOCSTRING is documentation for the function.
1882 Fourth arg INTERACTIVE if non-nil says function can be called interactively.
1883 Fifth arg TYPE indicates the type of the object:
1884 nil or omitted says FUNCTION is a function,
1885 `keymap' says FUNCTION is really a keymap, and
1886 `macro' or t says FUNCTION is really a macro.
1887 Third through fifth args give info about the real definition.
1888 They default to nil.
1889 If FUNCTION is already defined other than as an autoload,
1890 this does nothing and returns nil. */)
1891 (Lisp_Object function, Lisp_Object file, Lisp_Object docstring, Lisp_Object interactive, Lisp_Object type)
1893 CHECK_SYMBOL (function);
1894 CHECK_STRING (file);
1896 /* If function is defined and not as an autoload, don't override. */
1897 if (!NILP (XSYMBOL (function)->function)
1898 && !AUTOLOADP (XSYMBOL (function)->function))
1899 return Qnil;
1901 if (!NILP (Vpurify_flag) && EQ (docstring, make_number (0)))
1902 /* `read1' in lread.c has found the docstring starting with "\
1903 and assumed the docstring will be provided by Snarf-documentation, so it
1904 passed us 0 instead. But that leads to accidental sharing in purecopy's
1905 hash-consing, so we use a (hopefully) unique integer instead. */
1906 docstring = make_number (XHASH (function));
1907 return Fdefalias (function,
1908 list5 (Qautoload, file, docstring, interactive, type),
1909 Qnil);
1912 void
1913 un_autoload (Lisp_Object oldqueue)
1915 Lisp_Object queue, first, second;
1917 /* Queue to unwind is current value of Vautoload_queue.
1918 oldqueue is the shadowed value to leave in Vautoload_queue. */
1919 queue = Vautoload_queue;
1920 Vautoload_queue = oldqueue;
1921 while (CONSP (queue))
1923 first = XCAR (queue);
1924 second = Fcdr (first);
1925 first = Fcar (first);
1926 if (EQ (first, make_number (0)))
1927 Vfeatures = second;
1928 else
1929 Ffset (first, second);
1930 queue = XCDR (queue);
1934 /* Load an autoloaded function.
1935 FUNNAME is the symbol which is the function's name.
1936 FUNDEF is the autoload definition (a list). */
1938 DEFUN ("autoload-do-load", Fautoload_do_load, Sautoload_do_load, 1, 3, 0,
1939 doc: /* Load FUNDEF which should be an autoload.
1940 If non-nil, FUNNAME should be the symbol whose function value is FUNDEF,
1941 in which case the function returns the new autoloaded function value.
1942 If equal to `macro', MACRO-ONLY specifies that FUNDEF should only be loaded if
1943 it defines a macro. */)
1944 (Lisp_Object fundef, Lisp_Object funname, Lisp_Object macro_only)
1946 ptrdiff_t count = SPECPDL_INDEX ();
1948 if (!CONSP (fundef) || !EQ (Qautoload, XCAR (fundef)))
1949 return fundef;
1951 if (EQ (macro_only, Qmacro))
1953 Lisp_Object kind = Fnth (make_number (4), fundef);
1954 if (! (EQ (kind, Qt) || EQ (kind, Qmacro)))
1955 return fundef;
1958 /* This is to make sure that loadup.el gives a clear picture
1959 of what files are preloaded and when. */
1960 if (! NILP (Vpurify_flag))
1961 error ("Attempt to autoload %s while preparing to dump",
1962 SDATA (SYMBOL_NAME (funname)));
1964 CHECK_SYMBOL (funname);
1966 /* Preserve the match data. */
1967 record_unwind_save_match_data ();
1969 /* If autoloading gets an error (which includes the error of failing
1970 to define the function being called), we use Vautoload_queue
1971 to undo function definitions and `provide' calls made by
1972 the function. We do this in the specific case of autoloading
1973 because autoloading is not an explicit request "load this file",
1974 but rather a request to "call this function".
1976 The value saved here is to be restored into Vautoload_queue. */
1977 record_unwind_protect (un_autoload, Vautoload_queue);
1978 Vautoload_queue = Qt;
1979 /* If `macro_only', assume this autoload to be a "best-effort",
1980 so don't signal an error if autoloading fails. */
1981 Fload (Fcar (Fcdr (fundef)), macro_only, Qt, Qnil, Qt);
1983 /* Once loading finishes, don't undo it. */
1984 Vautoload_queue = Qt;
1985 unbind_to (count, Qnil);
1987 if (NILP (funname))
1988 return Qnil;
1989 else
1991 Lisp_Object fun = Findirect_function (funname, Qnil);
1993 if (!NILP (Fequal (fun, fundef)))
1994 error ("Autoloading failed to define function %s",
1995 SDATA (SYMBOL_NAME (funname)));
1996 else
1997 return fun;
2002 DEFUN ("eval", Feval, Seval, 1, 2, 0,
2003 doc: /* Evaluate FORM and return its value.
2004 If LEXICAL is t, evaluate using lexical scoping.
2005 LEXICAL can also be an actual lexical environment, in the form of an
2006 alist mapping symbols to their value. */)
2007 (Lisp_Object form, Lisp_Object lexical)
2009 ptrdiff_t count = SPECPDL_INDEX ();
2010 specbind (Qinternal_interpreter_environment,
2011 CONSP (lexical) || NILP (lexical) ? lexical : list1 (Qt));
2012 return unbind_to (count, eval_sub (form));
2015 /* Grow the specpdl stack by one entry.
2016 The caller should have already initialized the entry.
2017 Signal an error on stack overflow.
2019 Make sure that there is always one unused entry past the top of the
2020 stack, so that the just-initialized entry is safely unwound if
2021 memory exhausted and an error is signaled here. Also, allocate a
2022 never-used entry just before the bottom of the stack; sometimes its
2023 address is taken. */
2025 static void
2026 grow_specpdl (void)
2028 specpdl_ptr++;
2030 if (specpdl_ptr == specpdl + specpdl_size)
2032 ptrdiff_t count = SPECPDL_INDEX ();
2033 ptrdiff_t max_size = min (max_specpdl_size, PTRDIFF_MAX - 1000);
2034 union specbinding *pdlvec = specpdl - 1;
2035 ptrdiff_t pdlvecsize = specpdl_size + 1;
2036 if (max_size <= specpdl_size)
2038 if (max_specpdl_size < 400)
2039 max_size = max_specpdl_size = 400;
2040 if (max_size <= specpdl_size)
2041 signal_error ("Variable binding depth exceeds max-specpdl-size",
2042 Qnil);
2044 pdlvec = xpalloc (pdlvec, &pdlvecsize, 1, max_size + 1, sizeof *specpdl);
2045 specpdl = pdlvec + 1;
2046 specpdl_size = pdlvecsize - 1;
2047 specpdl_ptr = specpdl + count;
2051 ptrdiff_t
2052 record_in_backtrace (Lisp_Object function, Lisp_Object *args, ptrdiff_t nargs)
2054 ptrdiff_t count = SPECPDL_INDEX ();
2056 eassert (nargs >= UNEVALLED);
2057 specpdl_ptr->bt.kind = SPECPDL_BACKTRACE;
2058 specpdl_ptr->bt.debug_on_exit = false;
2059 specpdl_ptr->bt.function = function;
2060 specpdl_ptr->bt.args = args;
2061 specpdl_ptr->bt.nargs = nargs;
2062 grow_specpdl ();
2064 return count;
2067 /* Eval a sub-expression of the current expression (i.e. in the same
2068 lexical scope). */
2069 Lisp_Object
2070 eval_sub (Lisp_Object form)
2072 Lisp_Object fun, val, original_fun, original_args;
2073 Lisp_Object funcar;
2074 ptrdiff_t count;
2076 /* Declare here, as this array may be accessed by call_debugger near
2077 the end of this function. See Bug#21245. */
2078 Lisp_Object argvals[8];
2080 if (SYMBOLP (form))
2082 /* Look up its binding in the lexical environment.
2083 We do not pay attention to the declared_special flag here, since we
2084 already did that when let-binding the variable. */
2085 Lisp_Object lex_binding
2086 = !NILP (Vinternal_interpreter_environment) /* Mere optimization! */
2087 ? Fassq (form, Vinternal_interpreter_environment)
2088 : Qnil;
2089 if (CONSP (lex_binding))
2090 return XCDR (lex_binding);
2091 else
2092 return Fsymbol_value (form);
2095 if (!CONSP (form))
2096 return form;
2098 QUIT;
2100 maybe_gc ();
2102 if (++lisp_eval_depth > max_lisp_eval_depth)
2104 if (max_lisp_eval_depth < 100)
2105 max_lisp_eval_depth = 100;
2106 if (lisp_eval_depth > max_lisp_eval_depth)
2107 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2110 original_fun = XCAR (form);
2111 original_args = XCDR (form);
2113 /* This also protects them from gc. */
2114 count = record_in_backtrace (original_fun, &original_args, UNEVALLED);
2116 if (debug_on_next_call)
2117 do_debug_on_call (Qt, count);
2119 /* At this point, only original_fun and original_args
2120 have values that will be used below. */
2121 retry:
2123 /* Optimize for no indirection. */
2124 fun = original_fun;
2125 if (!SYMBOLP (fun))
2126 fun = Ffunction (Fcons (fun, Qnil));
2127 else if (!NILP (fun) && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2128 fun = indirect_function (fun);
2130 if (SUBRP (fun))
2132 Lisp_Object args_left = original_args;
2133 Lisp_Object numargs = Flength (args_left);
2135 check_cons_list ();
2137 if (XINT (numargs) < XSUBR (fun)->min_args
2138 || (XSUBR (fun)->max_args >= 0
2139 && XSUBR (fun)->max_args < XINT (numargs)))
2140 xsignal2 (Qwrong_number_of_arguments, original_fun, numargs);
2142 else if (XSUBR (fun)->max_args == UNEVALLED)
2143 val = (XSUBR (fun)->function.aUNEVALLED) (args_left);
2144 else if (XSUBR (fun)->max_args == MANY)
2146 /* Pass a vector of evaluated arguments. */
2147 Lisp_Object *vals;
2148 ptrdiff_t argnum = 0;
2149 USE_SAFE_ALLOCA;
2151 SAFE_ALLOCA_LISP (vals, XINT (numargs));
2153 while (!NILP (args_left))
2155 vals[argnum++] = eval_sub (Fcar (args_left));
2156 args_left = Fcdr (args_left);
2159 set_backtrace_args (specpdl + count, vals, XINT (numargs));
2161 val = (XSUBR (fun)->function.aMANY) (XINT (numargs), vals);
2163 check_cons_list ();
2164 lisp_eval_depth--;
2165 /* Do the debug-on-exit now, while VALS still exists. */
2166 if (backtrace_debug_on_exit (specpdl + count))
2167 val = call_debugger (list2 (Qexit, val));
2168 SAFE_FREE ();
2169 specpdl_ptr--;
2170 return val;
2172 else
2174 int i, maxargs = XSUBR (fun)->max_args;
2176 for (i = 0; i < maxargs; i++)
2178 argvals[i] = eval_sub (Fcar (args_left));
2179 args_left = Fcdr (args_left);
2182 set_backtrace_args (specpdl + count, argvals, XINT (numargs));
2184 switch (i)
2186 case 0:
2187 val = (XSUBR (fun)->function.a0 ());
2188 break;
2189 case 1:
2190 val = (XSUBR (fun)->function.a1 (argvals[0]));
2191 break;
2192 case 2:
2193 val = (XSUBR (fun)->function.a2 (argvals[0], argvals[1]));
2194 break;
2195 case 3:
2196 val = (XSUBR (fun)->function.a3
2197 (argvals[0], argvals[1], argvals[2]));
2198 break;
2199 case 4:
2200 val = (XSUBR (fun)->function.a4
2201 (argvals[0], argvals[1], argvals[2], argvals[3]));
2202 break;
2203 case 5:
2204 val = (XSUBR (fun)->function.a5
2205 (argvals[0], argvals[1], argvals[2], argvals[3],
2206 argvals[4]));
2207 break;
2208 case 6:
2209 val = (XSUBR (fun)->function.a6
2210 (argvals[0], argvals[1], argvals[2], argvals[3],
2211 argvals[4], argvals[5]));
2212 break;
2213 case 7:
2214 val = (XSUBR (fun)->function.a7
2215 (argvals[0], argvals[1], argvals[2], argvals[3],
2216 argvals[4], argvals[5], argvals[6]));
2217 break;
2219 case 8:
2220 val = (XSUBR (fun)->function.a8
2221 (argvals[0], argvals[1], argvals[2], argvals[3],
2222 argvals[4], argvals[5], argvals[6], argvals[7]));
2223 break;
2225 default:
2226 /* Someone has created a subr that takes more arguments than
2227 is supported by this code. We need to either rewrite the
2228 subr to use a different argument protocol, or add more
2229 cases to this switch. */
2230 emacs_abort ();
2234 else if (COMPILEDP (fun))
2235 return apply_lambda (fun, original_args, count);
2236 else
2238 if (NILP (fun))
2239 xsignal1 (Qvoid_function, original_fun);
2240 if (!CONSP (fun))
2241 xsignal1 (Qinvalid_function, original_fun);
2242 funcar = XCAR (fun);
2243 if (!SYMBOLP (funcar))
2244 xsignal1 (Qinvalid_function, original_fun);
2245 if (EQ (funcar, Qautoload))
2247 Fautoload_do_load (fun, original_fun, Qnil);
2248 goto retry;
2250 if (EQ (funcar, Qmacro))
2252 ptrdiff_t count1 = SPECPDL_INDEX ();
2253 Lisp_Object exp;
2254 /* Bind lexical-binding during expansion of the macro, so the
2255 macro can know reliably if the code it outputs will be
2256 interpreted using lexical-binding or not. */
2257 specbind (Qlexical_binding,
2258 NILP (Vinternal_interpreter_environment) ? Qnil : Qt);
2259 exp = apply1 (Fcdr (fun), original_args);
2260 unbind_to (count1, Qnil);
2261 val = eval_sub (exp);
2263 else if (EQ (funcar, Qlambda)
2264 || EQ (funcar, Qclosure))
2265 return apply_lambda (fun, original_args, count);
2266 else
2267 xsignal1 (Qinvalid_function, original_fun);
2269 check_cons_list ();
2271 lisp_eval_depth--;
2272 if (backtrace_debug_on_exit (specpdl + count))
2273 val = call_debugger (list2 (Qexit, val));
2274 specpdl_ptr--;
2276 return val;
2279 DEFUN ("apply", Fapply, Sapply, 1, MANY, 0,
2280 doc: /* Call FUNCTION with our remaining args, using our last arg as list of args.
2281 Then return the value FUNCTION returns.
2282 Thus, (apply \\='+ 1 2 \\='(3 4)) returns 10.
2283 usage: (apply FUNCTION &rest ARGUMENTS) */)
2284 (ptrdiff_t nargs, Lisp_Object *args)
2286 ptrdiff_t i, numargs, funcall_nargs;
2287 register Lisp_Object *funcall_args = NULL;
2288 register Lisp_Object spread_arg = args[nargs - 1];
2289 Lisp_Object fun = args[0];
2290 Lisp_Object retval;
2291 USE_SAFE_ALLOCA;
2293 CHECK_LIST (spread_arg);
2295 numargs = XINT (Flength (spread_arg));
2297 if (numargs == 0)
2298 return Ffuncall (nargs - 1, args);
2299 else if (numargs == 1)
2301 args [nargs - 1] = XCAR (spread_arg);
2302 return Ffuncall (nargs, args);
2305 numargs += nargs - 2;
2307 /* Optimize for no indirection. */
2308 if (SYMBOLP (fun) && !NILP (fun)
2309 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2311 fun = indirect_function (fun);
2312 if (NILP (fun))
2313 /* Let funcall get the error. */
2314 fun = args[0];
2317 if (SUBRP (fun) && XSUBR (fun)->max_args > numargs
2318 /* Don't hide an error by adding missing arguments. */
2319 && numargs >= XSUBR (fun)->min_args)
2321 /* Avoid making funcall cons up a yet another new vector of arguments
2322 by explicitly supplying nil's for optional values. */
2323 SAFE_ALLOCA_LISP (funcall_args, 1 + XSUBR (fun)->max_args);
2324 memclear (funcall_args + numargs + 1,
2325 (XSUBR (fun)->max_args - numargs) * word_size);
2326 funcall_nargs = 1 + XSUBR (fun)->max_args;
2328 else
2329 { /* We add 1 to numargs because funcall_args includes the
2330 function itself as well as its arguments. */
2331 SAFE_ALLOCA_LISP (funcall_args, 1 + numargs);
2332 funcall_nargs = 1 + numargs;
2335 memcpy (funcall_args, args, nargs * word_size);
2336 /* Spread the last arg we got. Its first element goes in
2337 the slot that it used to occupy, hence this value of I. */
2338 i = nargs - 1;
2339 while (!NILP (spread_arg))
2341 funcall_args [i++] = XCAR (spread_arg);
2342 spread_arg = XCDR (spread_arg);
2345 retval = Ffuncall (funcall_nargs, funcall_args);
2347 SAFE_FREE ();
2348 return retval;
2351 /* Run hook variables in various ways. */
2353 static Lisp_Object
2354 funcall_nil (ptrdiff_t nargs, Lisp_Object *args)
2356 Ffuncall (nargs, args);
2357 return Qnil;
2360 DEFUN ("run-hooks", Frun_hooks, Srun_hooks, 0, MANY, 0,
2361 doc: /* Run each hook in HOOKS.
2362 Each argument should be a symbol, a hook variable.
2363 These symbols are processed in the order specified.
2364 If a hook symbol has a non-nil value, that value may be a function
2365 or a list of functions to be called to run the hook.
2366 If the value is a function, it is called with no arguments.
2367 If it is a list, the elements are called, in order, with no arguments.
2369 Major modes should not use this function directly to run their mode
2370 hook; they should use `run-mode-hooks' instead.
2372 Do not use `make-local-variable' to make a hook variable buffer-local.
2373 Instead, use `add-hook' and specify t for the LOCAL argument.
2374 usage: (run-hooks &rest HOOKS) */)
2375 (ptrdiff_t nargs, Lisp_Object *args)
2377 ptrdiff_t i;
2379 for (i = 0; i < nargs; i++)
2380 run_hook (args[i]);
2382 return Qnil;
2385 DEFUN ("run-hook-with-args", Frun_hook_with_args,
2386 Srun_hook_with_args, 1, MANY, 0,
2387 doc: /* Run HOOK with the specified arguments ARGS.
2388 HOOK should be a symbol, a hook variable. The value of HOOK
2389 may be nil, a function, or a list of functions. Call each
2390 function in order with arguments ARGS. The final return value
2391 is unspecified.
2393 Do not use `make-local-variable' to make a hook variable buffer-local.
2394 Instead, use `add-hook' and specify t for the LOCAL argument.
2395 usage: (run-hook-with-args HOOK &rest ARGS) */)
2396 (ptrdiff_t nargs, Lisp_Object *args)
2398 return run_hook_with_args (nargs, args, funcall_nil);
2401 /* NB this one still documents a specific non-nil return value.
2402 (As did run-hook-with-args and run-hook-with-args-until-failure
2403 until they were changed in 24.1.) */
2404 DEFUN ("run-hook-with-args-until-success", Frun_hook_with_args_until_success,
2405 Srun_hook_with_args_until_success, 1, MANY, 0,
2406 doc: /* Run HOOK with the specified arguments ARGS.
2407 HOOK should be a symbol, a hook variable. The value of HOOK
2408 may be nil, a function, or a list of functions. Call each
2409 function in order with arguments ARGS, stopping at the first
2410 one that returns non-nil, and return that value. Otherwise (if
2411 all functions return nil, or if there are no functions to call),
2412 return nil.
2414 Do not use `make-local-variable' to make a hook variable buffer-local.
2415 Instead, use `add-hook' and specify t for the LOCAL argument.
2416 usage: (run-hook-with-args-until-success HOOK &rest ARGS) */)
2417 (ptrdiff_t nargs, Lisp_Object *args)
2419 return run_hook_with_args (nargs, args, Ffuncall);
2422 static Lisp_Object
2423 funcall_not (ptrdiff_t nargs, Lisp_Object *args)
2425 return NILP (Ffuncall (nargs, args)) ? Qt : Qnil;
2428 DEFUN ("run-hook-with-args-until-failure", Frun_hook_with_args_until_failure,
2429 Srun_hook_with_args_until_failure, 1, MANY, 0,
2430 doc: /* Run HOOK with the specified arguments ARGS.
2431 HOOK should be a symbol, a hook variable. The value of HOOK
2432 may be nil, a function, or a list of functions. Call each
2433 function in order with arguments ARGS, stopping at the first
2434 one that returns nil, and return nil. Otherwise (if all functions
2435 return non-nil, or if there are no functions to call), return non-nil
2436 \(do not rely on the precise return value in this case).
2438 Do not use `make-local-variable' to make a hook variable buffer-local.
2439 Instead, use `add-hook' and specify t for the LOCAL argument.
2440 usage: (run-hook-with-args-until-failure HOOK &rest ARGS) */)
2441 (ptrdiff_t nargs, Lisp_Object *args)
2443 return NILP (run_hook_with_args (nargs, args, funcall_not)) ? Qt : Qnil;
2446 static Lisp_Object
2447 run_hook_wrapped_funcall (ptrdiff_t nargs, Lisp_Object *args)
2449 Lisp_Object tmp = args[0], ret;
2450 args[0] = args[1];
2451 args[1] = tmp;
2452 ret = Ffuncall (nargs, args);
2453 args[1] = args[0];
2454 args[0] = tmp;
2455 return ret;
2458 DEFUN ("run-hook-wrapped", Frun_hook_wrapped, Srun_hook_wrapped, 2, MANY, 0,
2459 doc: /* Run HOOK, passing each function through WRAP-FUNCTION.
2460 I.e. instead of calling each function FUN directly with arguments ARGS,
2461 it calls WRAP-FUNCTION with arguments FUN and ARGS.
2462 As soon as a call to WRAP-FUNCTION returns non-nil, `run-hook-wrapped'
2463 aborts and returns that value.
2464 usage: (run-hook-wrapped HOOK WRAP-FUNCTION &rest ARGS) */)
2465 (ptrdiff_t nargs, Lisp_Object *args)
2467 return run_hook_with_args (nargs, args, run_hook_wrapped_funcall);
2470 /* ARGS[0] should be a hook symbol.
2471 Call each of the functions in the hook value, passing each of them
2472 as arguments all the rest of ARGS (all NARGS - 1 elements).
2473 FUNCALL specifies how to call each function on the hook. */
2475 Lisp_Object
2476 run_hook_with_args (ptrdiff_t nargs, Lisp_Object *args,
2477 Lisp_Object (*funcall) (ptrdiff_t nargs, Lisp_Object *args))
2479 Lisp_Object sym, val, ret = Qnil;
2481 /* If we are dying or still initializing,
2482 don't do anything--it would probably crash if we tried. */
2483 if (NILP (Vrun_hooks))
2484 return Qnil;
2486 sym = args[0];
2487 val = find_symbol_value (sym);
2489 if (EQ (val, Qunbound) || NILP (val))
2490 return ret;
2491 else if (!CONSP (val) || FUNCTIONP (val))
2493 args[0] = val;
2494 return funcall (nargs, args);
2496 else
2498 Lisp_Object global_vals = Qnil;
2500 for (;
2501 CONSP (val) && NILP (ret);
2502 val = XCDR (val))
2504 if (EQ (XCAR (val), Qt))
2506 /* t indicates this hook has a local binding;
2507 it means to run the global binding too. */
2508 global_vals = Fdefault_value (sym);
2509 if (NILP (global_vals)) continue;
2511 if (!CONSP (global_vals) || EQ (XCAR (global_vals), Qlambda))
2513 args[0] = global_vals;
2514 ret = funcall (nargs, args);
2516 else
2518 for (;
2519 CONSP (global_vals) && NILP (ret);
2520 global_vals = XCDR (global_vals))
2522 args[0] = XCAR (global_vals);
2523 /* In a global value, t should not occur. If it does, we
2524 must ignore it to avoid an endless loop. */
2525 if (!EQ (args[0], Qt))
2526 ret = funcall (nargs, args);
2530 else
2532 args[0] = XCAR (val);
2533 ret = funcall (nargs, args);
2537 return ret;
2541 /* Run the hook HOOK, giving each function no args. */
2543 void
2544 run_hook (Lisp_Object hook)
2546 Frun_hook_with_args (1, &hook);
2549 /* Run the hook HOOK, giving each function the two args ARG1 and ARG2. */
2551 void
2552 run_hook_with_args_2 (Lisp_Object hook, Lisp_Object arg1, Lisp_Object arg2)
2554 CALLN (Frun_hook_with_args, hook, arg1, arg2);
2557 /* Apply fn to arg. */
2558 Lisp_Object
2559 apply1 (Lisp_Object fn, Lisp_Object arg)
2561 return NILP (arg) ? Ffuncall (1, &fn) : CALLN (Fapply, fn, arg);
2564 /* Call function fn on no arguments. */
2565 Lisp_Object
2566 call0 (Lisp_Object fn)
2568 return Ffuncall (1, &fn);
2571 /* Call function fn with 1 argument arg1. */
2572 /* ARGSUSED */
2573 Lisp_Object
2574 call1 (Lisp_Object fn, Lisp_Object arg1)
2576 return CALLN (Ffuncall, fn, arg1);
2579 /* Call function fn with 2 arguments arg1, arg2. */
2580 /* ARGSUSED */
2581 Lisp_Object
2582 call2 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2)
2584 return CALLN (Ffuncall, fn, arg1, arg2);
2587 /* Call function fn with 3 arguments arg1, arg2, arg3. */
2588 /* ARGSUSED */
2589 Lisp_Object
2590 call3 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2592 return CALLN (Ffuncall, fn, arg1, arg2, arg3);
2595 /* Call function fn with 4 arguments arg1, arg2, arg3, arg4. */
2596 /* ARGSUSED */
2597 Lisp_Object
2598 call4 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2599 Lisp_Object arg4)
2601 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4);
2604 /* Call function fn with 5 arguments arg1, arg2, arg3, arg4, arg5. */
2605 /* ARGSUSED */
2606 Lisp_Object
2607 call5 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2608 Lisp_Object arg4, Lisp_Object arg5)
2610 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5);
2613 /* Call function fn with 6 arguments arg1, arg2, arg3, arg4, arg5, arg6. */
2614 /* ARGSUSED */
2615 Lisp_Object
2616 call6 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2617 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6)
2619 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6);
2622 /* Call function fn with 7 arguments arg1, arg2, arg3, arg4, arg5, arg6, arg7. */
2623 /* ARGSUSED */
2624 Lisp_Object
2625 call7 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2626 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6, Lisp_Object arg7)
2628 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
2631 DEFUN ("functionp", Ffunctionp, Sfunctionp, 1, 1, 0,
2632 doc: /* Non-nil if OBJECT is a function. */)
2633 (Lisp_Object object)
2635 if (FUNCTIONP (object))
2636 return Qt;
2637 return Qnil;
2640 DEFUN ("funcall", Ffuncall, Sfuncall, 1, MANY, 0,
2641 doc: /* Call first argument as a function, passing remaining arguments to it.
2642 Return the value that function returns.
2643 Thus, (funcall \\='cons \\='x \\='y) returns (x . y).
2644 usage: (funcall FUNCTION &rest ARGUMENTS) */)
2645 (ptrdiff_t nargs, Lisp_Object *args)
2647 Lisp_Object fun, original_fun;
2648 Lisp_Object funcar;
2649 ptrdiff_t numargs = nargs - 1;
2650 Lisp_Object lisp_numargs;
2651 Lisp_Object val;
2652 Lisp_Object *internal_args;
2653 ptrdiff_t count;
2655 QUIT;
2657 if (++lisp_eval_depth > max_lisp_eval_depth)
2659 if (max_lisp_eval_depth < 100)
2660 max_lisp_eval_depth = 100;
2661 if (lisp_eval_depth > max_lisp_eval_depth)
2662 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2665 count = record_in_backtrace (args[0], &args[1], nargs - 1);
2667 maybe_gc ();
2669 if (debug_on_next_call)
2670 do_debug_on_call (Qlambda, count);
2672 check_cons_list ();
2674 original_fun = args[0];
2676 retry:
2678 /* Optimize for no indirection. */
2679 fun = original_fun;
2680 if (SYMBOLP (fun) && !NILP (fun)
2681 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2682 fun = indirect_function (fun);
2684 if (SUBRP (fun))
2686 if (numargs < XSUBR (fun)->min_args
2687 || (XSUBR (fun)->max_args >= 0 && XSUBR (fun)->max_args < numargs))
2689 XSETFASTINT (lisp_numargs, numargs);
2690 xsignal2 (Qwrong_number_of_arguments, original_fun, lisp_numargs);
2693 else if (XSUBR (fun)->max_args == UNEVALLED)
2694 xsignal1 (Qinvalid_function, original_fun);
2696 else if (XSUBR (fun)->max_args == MANY)
2697 val = (XSUBR (fun)->function.aMANY) (numargs, args + 1);
2698 else
2700 Lisp_Object internal_argbuf[8];
2701 if (XSUBR (fun)->max_args > numargs)
2703 eassert (XSUBR (fun)->max_args <= ARRAYELTS (internal_argbuf));
2704 internal_args = internal_argbuf;
2705 memcpy (internal_args, args + 1, numargs * word_size);
2706 memclear (internal_args + numargs,
2707 (XSUBR (fun)->max_args - numargs) * word_size);
2709 else
2710 internal_args = args + 1;
2711 switch (XSUBR (fun)->max_args)
2713 case 0:
2714 val = (XSUBR (fun)->function.a0 ());
2715 break;
2716 case 1:
2717 val = (XSUBR (fun)->function.a1 (internal_args[0]));
2718 break;
2719 case 2:
2720 val = (XSUBR (fun)->function.a2
2721 (internal_args[0], internal_args[1]));
2722 break;
2723 case 3:
2724 val = (XSUBR (fun)->function.a3
2725 (internal_args[0], internal_args[1], internal_args[2]));
2726 break;
2727 case 4:
2728 val = (XSUBR (fun)->function.a4
2729 (internal_args[0], internal_args[1], internal_args[2],
2730 internal_args[3]));
2731 break;
2732 case 5:
2733 val = (XSUBR (fun)->function.a5
2734 (internal_args[0], internal_args[1], internal_args[2],
2735 internal_args[3], internal_args[4]));
2736 break;
2737 case 6:
2738 val = (XSUBR (fun)->function.a6
2739 (internal_args[0], internal_args[1], internal_args[2],
2740 internal_args[3], internal_args[4], internal_args[5]));
2741 break;
2742 case 7:
2743 val = (XSUBR (fun)->function.a7
2744 (internal_args[0], internal_args[1], internal_args[2],
2745 internal_args[3], internal_args[4], internal_args[5],
2746 internal_args[6]));
2747 break;
2749 case 8:
2750 val = (XSUBR (fun)->function.a8
2751 (internal_args[0], internal_args[1], internal_args[2],
2752 internal_args[3], internal_args[4], internal_args[5],
2753 internal_args[6], internal_args[7]));
2754 break;
2756 default:
2758 /* If a subr takes more than 8 arguments without using MANY
2759 or UNEVALLED, we need to extend this function to support it.
2760 Until this is done, there is no way to call the function. */
2761 emacs_abort ();
2765 else if (COMPILEDP (fun))
2766 val = funcall_lambda (fun, numargs, args + 1);
2767 else
2769 if (NILP (fun))
2770 xsignal1 (Qvoid_function, original_fun);
2771 if (!CONSP (fun))
2772 xsignal1 (Qinvalid_function, original_fun);
2773 funcar = XCAR (fun);
2774 if (!SYMBOLP (funcar))
2775 xsignal1 (Qinvalid_function, original_fun);
2776 if (EQ (funcar, Qlambda)
2777 || EQ (funcar, Qclosure))
2778 val = funcall_lambda (fun, numargs, args + 1);
2779 else if (EQ (funcar, Qautoload))
2781 Fautoload_do_load (fun, original_fun, Qnil);
2782 check_cons_list ();
2783 goto retry;
2785 else
2786 xsignal1 (Qinvalid_function, original_fun);
2788 check_cons_list ();
2789 lisp_eval_depth--;
2790 if (backtrace_debug_on_exit (specpdl + count))
2791 val = call_debugger (list2 (Qexit, val));
2792 specpdl_ptr--;
2793 return val;
2796 static Lisp_Object
2797 apply_lambda (Lisp_Object fun, Lisp_Object args, ptrdiff_t count)
2799 Lisp_Object args_left;
2800 ptrdiff_t i;
2801 EMACS_INT numargs;
2802 Lisp_Object *arg_vector;
2803 Lisp_Object tem;
2804 USE_SAFE_ALLOCA;
2806 numargs = XFASTINT (Flength (args));
2807 SAFE_ALLOCA_LISP (arg_vector, numargs);
2808 args_left = args;
2810 for (i = 0; i < numargs; )
2812 tem = Fcar (args_left), args_left = Fcdr (args_left);
2813 tem = eval_sub (tem);
2814 arg_vector[i++] = tem;
2817 set_backtrace_args (specpdl + count, arg_vector, i);
2818 tem = funcall_lambda (fun, numargs, arg_vector);
2820 check_cons_list ();
2821 lisp_eval_depth--;
2822 /* Do the debug-on-exit now, while arg_vector still exists. */
2823 if (backtrace_debug_on_exit (specpdl + count))
2824 tem = call_debugger (list2 (Qexit, tem));
2825 SAFE_FREE ();
2826 specpdl_ptr--;
2827 return tem;
2830 /* Apply a Lisp function FUN to the NARGS evaluated arguments in ARG_VECTOR
2831 and return the result of evaluation.
2832 FUN must be either a lambda-expression or a compiled-code object. */
2834 static Lisp_Object
2835 funcall_lambda (Lisp_Object fun, ptrdiff_t nargs,
2836 register Lisp_Object *arg_vector)
2838 Lisp_Object val, syms_left, next, lexenv;
2839 ptrdiff_t count = SPECPDL_INDEX ();
2840 ptrdiff_t i;
2841 bool optional, rest;
2843 if (CONSP (fun))
2845 if (EQ (XCAR (fun), Qclosure))
2847 fun = XCDR (fun); /* Drop `closure'. */
2848 lexenv = XCAR (fun);
2849 CHECK_LIST_CONS (fun, fun);
2851 else
2852 lexenv = Qnil;
2853 syms_left = XCDR (fun);
2854 if (CONSP (syms_left))
2855 syms_left = XCAR (syms_left);
2856 else
2857 xsignal1 (Qinvalid_function, fun);
2859 else if (COMPILEDP (fun))
2861 ptrdiff_t size = ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK;
2862 if (size <= COMPILED_STACK_DEPTH)
2863 xsignal1 (Qinvalid_function, fun);
2864 syms_left = AREF (fun, COMPILED_ARGLIST);
2865 if (INTEGERP (syms_left))
2866 /* A byte-code object with an integer args template means we
2867 shouldn't bind any arguments, instead just call the byte-code
2868 interpreter directly; it will push arguments as necessary.
2870 Byte-code objects with a nil args template (the default)
2871 have dynamically-bound arguments, and use the
2872 argument-binding code below instead (as do all interpreted
2873 functions, even lexically bound ones). */
2875 /* If we have not actually read the bytecode string
2876 and constants vector yet, fetch them from the file. */
2877 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2878 Ffetch_bytecode (fun);
2879 return exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2880 AREF (fun, COMPILED_CONSTANTS),
2881 AREF (fun, COMPILED_STACK_DEPTH),
2882 syms_left,
2883 nargs, arg_vector);
2885 lexenv = Qnil;
2887 else
2888 emacs_abort ();
2890 i = optional = rest = 0;
2891 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
2893 QUIT;
2895 next = XCAR (syms_left);
2896 if (!SYMBOLP (next))
2897 xsignal1 (Qinvalid_function, fun);
2899 if (EQ (next, Qand_rest))
2900 rest = 1;
2901 else if (EQ (next, Qand_optional))
2902 optional = 1;
2903 else
2905 Lisp_Object arg;
2906 if (rest)
2908 arg = Flist (nargs - i, &arg_vector[i]);
2909 i = nargs;
2911 else if (i < nargs)
2912 arg = arg_vector[i++];
2913 else if (!optional)
2914 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2915 else
2916 arg = Qnil;
2918 /* Bind the argument. */
2919 if (!NILP (lexenv) && SYMBOLP (next))
2920 /* Lexically bind NEXT by adding it to the lexenv alist. */
2921 lexenv = Fcons (Fcons (next, arg), lexenv);
2922 else
2923 /* Dynamically bind NEXT. */
2924 specbind (next, arg);
2928 if (!NILP (syms_left))
2929 xsignal1 (Qinvalid_function, fun);
2930 else if (i < nargs)
2931 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2933 if (!EQ (lexenv, Vinternal_interpreter_environment))
2934 /* Instantiate a new lexical environment. */
2935 specbind (Qinternal_interpreter_environment, lexenv);
2937 if (CONSP (fun))
2938 val = Fprogn (XCDR (XCDR (fun)));
2939 else
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 val = exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2946 AREF (fun, COMPILED_CONSTANTS),
2947 AREF (fun, COMPILED_STACK_DEPTH),
2948 Qnil, 0, 0);
2951 return unbind_to (count, val);
2954 DEFUN ("func-arity", Ffunc_arity, Sfunc_arity, 1, 1, 0,
2955 doc: /* Return minimum and maximum number of args allowed for FUNCTION.
2956 FUNCTION must be a function of some kind.
2957 The returned value is a cons cell (MIN . MAX). MIN is the minimum number
2958 of args. MAX is the maximum number, or the symbol `many', for a
2959 function with `&rest' args, or `unevalled' for a special form. */)
2960 (Lisp_Object function)
2962 Lisp_Object original;
2963 Lisp_Object funcar;
2964 Lisp_Object result;
2966 original = function;
2968 retry:
2970 /* Optimize for no indirection. */
2971 function = original;
2972 if (SYMBOLP (function) && !NILP (function))
2974 function = XSYMBOL (function)->function;
2975 if (SYMBOLP (function))
2976 function = indirect_function (function);
2979 if (CONSP (function) && EQ (XCAR (function), Qmacro))
2980 function = XCDR (function);
2982 if (SUBRP (function))
2983 result = Fsubr_arity (function);
2984 else if (COMPILEDP (function))
2985 result = lambda_arity (function);
2986 else
2988 if (NILP (function))
2989 xsignal1 (Qvoid_function, original);
2990 if (!CONSP (function))
2991 xsignal1 (Qinvalid_function, original);
2992 funcar = XCAR (function);
2993 if (!SYMBOLP (funcar))
2994 xsignal1 (Qinvalid_function, original);
2995 if (EQ (funcar, Qlambda)
2996 || EQ (funcar, Qclosure))
2997 result = lambda_arity (function);
2998 else if (EQ (funcar, Qautoload))
3000 Fautoload_do_load (function, original, Qnil);
3001 goto retry;
3003 else
3004 xsignal1 (Qinvalid_function, original);
3006 return result;
3009 /* FUN must be either a lambda-expression or a compiled-code object. */
3010 static Lisp_Object
3011 lambda_arity (Lisp_Object fun)
3013 Lisp_Object syms_left;
3015 if (CONSP (fun))
3017 if (EQ (XCAR (fun), Qclosure))
3019 fun = XCDR (fun); /* Drop `closure'. */
3020 CHECK_LIST_CONS (fun, fun);
3022 syms_left = XCDR (fun);
3023 if (CONSP (syms_left))
3024 syms_left = XCAR (syms_left);
3025 else
3026 xsignal1 (Qinvalid_function, fun);
3028 else if (COMPILEDP (fun))
3030 ptrdiff_t size = ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK;
3031 if (size <= COMPILED_STACK_DEPTH)
3032 xsignal1 (Qinvalid_function, fun);
3033 syms_left = AREF (fun, COMPILED_ARGLIST);
3034 if (INTEGERP (syms_left))
3035 return get_byte_code_arity (syms_left);
3037 else
3038 emacs_abort ();
3040 EMACS_INT minargs = 0, maxargs = 0;
3041 bool optional = false;
3042 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
3044 Lisp_Object next = XCAR (syms_left);
3045 if (!SYMBOLP (next))
3046 xsignal1 (Qinvalid_function, fun);
3048 if (EQ (next, Qand_rest))
3049 return Fcons (make_number (minargs), Qmany);
3050 else if (EQ (next, Qand_optional))
3051 optional = true;
3052 else
3054 if (!optional)
3055 minargs++;
3056 maxargs++;
3060 if (!NILP (syms_left))
3061 xsignal1 (Qinvalid_function, fun);
3063 return Fcons (make_number (minargs), make_number (maxargs));
3066 DEFUN ("fetch-bytecode", Ffetch_bytecode, Sfetch_bytecode,
3067 1, 1, 0,
3068 doc: /* If byte-compiled OBJECT is lazy-loaded, fetch it now. */)
3069 (Lisp_Object object)
3071 Lisp_Object tem;
3073 if (COMPILEDP (object))
3075 ptrdiff_t size = ASIZE (object) & PSEUDOVECTOR_SIZE_MASK;
3076 if (size <= COMPILED_STACK_DEPTH)
3077 xsignal1 (Qinvalid_function, object);
3078 if (CONSP (AREF (object, COMPILED_BYTECODE)))
3080 tem = read_doc_string (AREF (object, COMPILED_BYTECODE));
3081 if (!CONSP (tem))
3083 tem = AREF (object, COMPILED_BYTECODE);
3084 if (CONSP (tem) && STRINGP (XCAR (tem)))
3085 error ("Invalid byte code in %s", SDATA (XCAR (tem)));
3086 else
3087 error ("Invalid byte code");
3089 ASET (object, COMPILED_BYTECODE, XCAR (tem));
3090 ASET (object, COMPILED_CONSTANTS, XCDR (tem));
3093 return object;
3096 /* Return true if SYMBOL currently has a let-binding
3097 which was made in the buffer that is now current. */
3099 bool
3100 let_shadows_buffer_binding_p (struct Lisp_Symbol *symbol)
3102 union specbinding *p;
3103 Lisp_Object buf = Fcurrent_buffer ();
3105 for (p = specpdl_ptr; p > specpdl; )
3106 if ((--p)->kind > SPECPDL_LET)
3108 struct Lisp_Symbol *let_bound_symbol = XSYMBOL (specpdl_symbol (p));
3109 eassert (let_bound_symbol->redirect != SYMBOL_VARALIAS);
3110 if (symbol == let_bound_symbol
3111 && EQ (specpdl_where (p), buf))
3112 return 1;
3115 return 0;
3118 bool
3119 let_shadows_global_binding_p (Lisp_Object symbol)
3121 union specbinding *p;
3123 for (p = specpdl_ptr; p > specpdl; )
3124 if ((--p)->kind >= SPECPDL_LET && EQ (specpdl_symbol (p), symbol))
3125 return 1;
3127 return 0;
3130 /* `specpdl_ptr' describes which variable is
3131 let-bound, so it can be properly undone when we unbind_to.
3132 It can be either a plain SPECPDL_LET or a SPECPDL_LET_LOCAL/DEFAULT.
3133 - SYMBOL is the variable being bound. Note that it should not be
3134 aliased (i.e. when let-binding V1 that's aliased to V2, we want
3135 to record V2 here).
3136 - WHERE tells us in which buffer the binding took place.
3137 This is used for SPECPDL_LET_LOCAL bindings (i.e. bindings to a
3138 buffer-local variable) as well as for SPECPDL_LET_DEFAULT bindings,
3139 i.e. bindings to the default value of a variable which can be
3140 buffer-local. */
3142 void
3143 specbind (Lisp_Object symbol, Lisp_Object value)
3145 struct Lisp_Symbol *sym;
3147 CHECK_SYMBOL (symbol);
3148 sym = XSYMBOL (symbol);
3150 start:
3151 switch (sym->redirect)
3153 case SYMBOL_VARALIAS:
3154 sym = indirect_variable (sym); XSETSYMBOL (symbol, sym); goto start;
3155 case SYMBOL_PLAINVAL:
3156 /* The most common case is that of a non-constant symbol with a
3157 trivial value. Make that as fast as we can. */
3158 specpdl_ptr->let.kind = SPECPDL_LET;
3159 specpdl_ptr->let.symbol = symbol;
3160 specpdl_ptr->let.old_value = SYMBOL_VAL (sym);
3161 grow_specpdl ();
3162 if (!sym->constant)
3163 SET_SYMBOL_VAL (sym, value);
3164 else
3165 set_internal (symbol, value, Qnil, 1);
3166 break;
3167 case SYMBOL_LOCALIZED:
3168 if (SYMBOL_BLV (sym)->frame_local)
3169 error ("Frame-local vars cannot be let-bound");
3170 case SYMBOL_FORWARDED:
3172 Lisp_Object ovalue = find_symbol_value (symbol);
3173 specpdl_ptr->let.kind = SPECPDL_LET_LOCAL;
3174 specpdl_ptr->let.symbol = symbol;
3175 specpdl_ptr->let.old_value = ovalue;
3176 specpdl_ptr->let.where = Fcurrent_buffer ();
3178 eassert (sym->redirect != SYMBOL_LOCALIZED
3179 || (EQ (SYMBOL_BLV (sym)->where, Fcurrent_buffer ())));
3181 if (sym->redirect == SYMBOL_LOCALIZED)
3183 if (!blv_found (SYMBOL_BLV (sym)))
3184 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3186 else if (BUFFER_OBJFWDP (SYMBOL_FWD (sym)))
3188 /* If SYMBOL is a per-buffer variable which doesn't have a
3189 buffer-local value here, make the `let' change the global
3190 value by changing the value of SYMBOL in all buffers not
3191 having their own value. This is consistent with what
3192 happens with other buffer-local variables. */
3193 if (NILP (Flocal_variable_p (symbol, Qnil)))
3195 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3196 grow_specpdl ();
3197 Fset_default (symbol, value);
3198 return;
3201 else
3202 specpdl_ptr->let.kind = SPECPDL_LET;
3204 grow_specpdl ();
3205 set_internal (symbol, value, Qnil, 1);
3206 break;
3208 default: emacs_abort ();
3212 /* Push unwind-protect entries of various types. */
3214 void
3215 record_unwind_protect (void (*function) (Lisp_Object), Lisp_Object arg)
3217 specpdl_ptr->unwind.kind = SPECPDL_UNWIND;
3218 specpdl_ptr->unwind.func = function;
3219 specpdl_ptr->unwind.arg = arg;
3220 grow_specpdl ();
3223 void
3224 record_unwind_protect_ptr (void (*function) (void *), void *arg)
3226 specpdl_ptr->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3227 specpdl_ptr->unwind_ptr.func = function;
3228 specpdl_ptr->unwind_ptr.arg = arg;
3229 grow_specpdl ();
3232 void
3233 record_unwind_protect_int (void (*function) (int), int arg)
3235 specpdl_ptr->unwind_int.kind = SPECPDL_UNWIND_INT;
3236 specpdl_ptr->unwind_int.func = function;
3237 specpdl_ptr->unwind_int.arg = arg;
3238 grow_specpdl ();
3241 void
3242 record_unwind_protect_void (void (*function) (void))
3244 specpdl_ptr->unwind_void.kind = SPECPDL_UNWIND_VOID;
3245 specpdl_ptr->unwind_void.func = function;
3246 grow_specpdl ();
3249 static void
3250 do_nothing (void)
3253 /* Push an unwind-protect entry that does nothing, so that
3254 set_unwind_protect_ptr can overwrite it later. */
3256 void
3257 record_unwind_protect_nothing (void)
3259 record_unwind_protect_void (do_nothing);
3262 /* Clear the unwind-protect entry COUNT, so that it does nothing.
3263 It need not be at the top of the stack. */
3265 void
3266 clear_unwind_protect (ptrdiff_t count)
3268 union specbinding *p = specpdl + count;
3269 p->unwind_void.kind = SPECPDL_UNWIND_VOID;
3270 p->unwind_void.func = do_nothing;
3273 /* Set the unwind-protect entry COUNT so that it invokes FUNC (ARG).
3274 It need not be at the top of the stack. Discard the entry's
3275 previous value without invoking it. */
3277 void
3278 set_unwind_protect (ptrdiff_t count, void (*func) (Lisp_Object),
3279 Lisp_Object arg)
3281 union specbinding *p = specpdl + count;
3282 p->unwind.kind = SPECPDL_UNWIND;
3283 p->unwind.func = func;
3284 p->unwind.arg = arg;
3287 void
3288 set_unwind_protect_ptr (ptrdiff_t count, void (*func) (void *), void *arg)
3290 union specbinding *p = specpdl + count;
3291 p->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3292 p->unwind_ptr.func = func;
3293 p->unwind_ptr.arg = arg;
3296 /* Pop and execute entries from the unwind-protect stack until the
3297 depth COUNT is reached. Return VALUE. */
3299 Lisp_Object
3300 unbind_to (ptrdiff_t count, Lisp_Object value)
3302 Lisp_Object quitf = Vquit_flag;
3304 Vquit_flag = Qnil;
3306 while (specpdl_ptr != specpdl + count)
3308 /* Decrement specpdl_ptr before we do the work to unbind it, so
3309 that an error in unbinding won't try to unbind the same entry
3310 again. Take care to copy any parts of the binding needed
3311 before invoking any code that can make more bindings. */
3313 specpdl_ptr--;
3315 switch (specpdl_ptr->kind)
3317 case SPECPDL_UNWIND:
3318 specpdl_ptr->unwind.func (specpdl_ptr->unwind.arg);
3319 break;
3320 case SPECPDL_UNWIND_PTR:
3321 specpdl_ptr->unwind_ptr.func (specpdl_ptr->unwind_ptr.arg);
3322 break;
3323 case SPECPDL_UNWIND_INT:
3324 specpdl_ptr->unwind_int.func (specpdl_ptr->unwind_int.arg);
3325 break;
3326 case SPECPDL_UNWIND_VOID:
3327 specpdl_ptr->unwind_void.func ();
3328 break;
3329 case SPECPDL_BACKTRACE:
3330 break;
3331 case SPECPDL_LET:
3332 { /* If variable has a trivial value (no forwarding), we can
3333 just set it. No need to check for constant symbols here,
3334 since that was already done by specbind. */
3335 Lisp_Object sym = specpdl_symbol (specpdl_ptr);
3336 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3338 SET_SYMBOL_VAL (XSYMBOL (sym),
3339 specpdl_old_value (specpdl_ptr));
3340 break;
3342 else
3343 { /* FALLTHROUGH!!
3344 NOTE: we only ever come here if make_local_foo was used for
3345 the first time on this var within this let. */
3348 case SPECPDL_LET_DEFAULT:
3349 Fset_default (specpdl_symbol (specpdl_ptr),
3350 specpdl_old_value (specpdl_ptr));
3351 break;
3352 case SPECPDL_LET_LOCAL:
3354 Lisp_Object symbol = specpdl_symbol (specpdl_ptr);
3355 Lisp_Object where = specpdl_where (specpdl_ptr);
3356 Lisp_Object old_value = specpdl_old_value (specpdl_ptr);
3357 eassert (BUFFERP (where));
3359 /* If this was a local binding, reset the value in the appropriate
3360 buffer, but only if that buffer's binding still exists. */
3361 if (!NILP (Flocal_variable_p (symbol, where)))
3362 set_internal (symbol, old_value, where, 1);
3364 break;
3368 if (NILP (Vquit_flag) && !NILP (quitf))
3369 Vquit_flag = quitf;
3371 return value;
3374 DEFUN ("special-variable-p", Fspecial_variable_p, Sspecial_variable_p, 1, 1, 0,
3375 doc: /* Return non-nil if SYMBOL's global binding has been declared special.
3376 A special variable is one that will be bound dynamically, even in a
3377 context where binding is lexical by default. */)
3378 (Lisp_Object symbol)
3380 CHECK_SYMBOL (symbol);
3381 return XSYMBOL (symbol)->declared_special ? Qt : Qnil;
3385 DEFUN ("backtrace-debug", Fbacktrace_debug, Sbacktrace_debug, 2, 2, 0,
3386 doc: /* Set the debug-on-exit flag of eval frame LEVEL levels down to FLAG.
3387 The debugger is entered when that frame exits, if the flag is non-nil. */)
3388 (Lisp_Object level, Lisp_Object flag)
3390 union specbinding *pdl = backtrace_top ();
3391 register EMACS_INT i;
3393 CHECK_NUMBER (level);
3395 for (i = 0; backtrace_p (pdl) && i < XINT (level); i++)
3396 pdl = backtrace_next (pdl);
3398 if (backtrace_p (pdl))
3399 set_backtrace_debug_on_exit (pdl, !NILP (flag));
3401 return flag;
3404 DEFUN ("backtrace", Fbacktrace, Sbacktrace, 0, 0, "",
3405 doc: /* Print a trace of Lisp function calls currently active.
3406 Output stream used is value of `standard-output'. */)
3407 (void)
3409 union specbinding *pdl = backtrace_top ();
3410 Lisp_Object tem;
3411 Lisp_Object old_print_level = Vprint_level;
3413 if (NILP (Vprint_level))
3414 XSETFASTINT (Vprint_level, 8);
3416 while (backtrace_p (pdl))
3418 write_string (backtrace_debug_on_exit (pdl) ? "* " : " ");
3419 if (backtrace_nargs (pdl) == UNEVALLED)
3421 Fprin1 (Fcons (backtrace_function (pdl), *backtrace_args (pdl)),
3422 Qnil);
3423 write_string ("\n");
3425 else
3427 tem = backtrace_function (pdl);
3428 Fprin1 (tem, Qnil); /* This can QUIT. */
3429 write_string ("(");
3431 ptrdiff_t i;
3432 for (i = 0; i < backtrace_nargs (pdl); i++)
3434 if (i) write_string (" ");
3435 Fprin1 (backtrace_args (pdl)[i], Qnil);
3438 write_string (")\n");
3440 pdl = backtrace_next (pdl);
3443 Vprint_level = old_print_level;
3444 return Qnil;
3447 static union specbinding *
3448 get_backtrace_frame (Lisp_Object nframes, Lisp_Object base)
3450 union specbinding *pdl = backtrace_top ();
3451 register EMACS_INT i;
3453 CHECK_NATNUM (nframes);
3455 if (!NILP (base))
3456 { /* Skip up to `base'. */
3457 base = Findirect_function (base, Qt);
3458 while (backtrace_p (pdl)
3459 && !EQ (base, Findirect_function (backtrace_function (pdl), Qt)))
3460 pdl = backtrace_next (pdl);
3463 /* Find the frame requested. */
3464 for (i = XFASTINT (nframes); i > 0 && backtrace_p (pdl); i--)
3465 pdl = backtrace_next (pdl);
3467 return pdl;
3470 DEFUN ("backtrace-frame", Fbacktrace_frame, Sbacktrace_frame, 1, 2, NULL,
3471 doc: /* Return the function and arguments NFRAMES up from current execution point.
3472 If that frame has not evaluated the arguments yet (or is a special form),
3473 the value is (nil FUNCTION ARG-FORMS...).
3474 If that frame has evaluated its arguments and called its function already,
3475 the value is (t FUNCTION ARG-VALUES...).
3476 A &rest arg is represented as the tail of the list ARG-VALUES.
3477 FUNCTION is whatever was supplied as car of evaluated list,
3478 or a lambda expression for macro calls.
3479 If NFRAMES is more than the number of frames, the value is nil.
3480 If BASE is non-nil, it should be a function and NFRAMES counts from its
3481 nearest activation frame. */)
3482 (Lisp_Object nframes, Lisp_Object base)
3484 union specbinding *pdl = get_backtrace_frame (nframes, base);
3486 if (!backtrace_p (pdl))
3487 return Qnil;
3488 if (backtrace_nargs (pdl) == UNEVALLED)
3489 return Fcons (Qnil,
3490 Fcons (backtrace_function (pdl), *backtrace_args (pdl)));
3491 else
3493 Lisp_Object tem = Flist (backtrace_nargs (pdl), backtrace_args (pdl));
3495 return Fcons (Qt, Fcons (backtrace_function (pdl), tem));
3499 /* For backtrace-eval, we want to temporarily unwind the last few elements of
3500 the specpdl stack, and then rewind them. We store the pre-unwind values
3501 directly in the pre-existing specpdl elements (i.e. we swap the current
3502 value and the old value stored in the specpdl), kind of like the inplace
3503 pointer-reversal trick. As it turns out, the rewind does the same as the
3504 unwind, except it starts from the other end of the specpdl stack, so we use
3505 the same function for both unwind and rewind. */
3506 static void
3507 backtrace_eval_unrewind (int distance)
3509 union specbinding *tmp = specpdl_ptr;
3510 int step = -1;
3511 if (distance < 0)
3512 { /* It's a rewind rather than unwind. */
3513 tmp += distance - 1;
3514 step = 1;
3515 distance = -distance;
3518 for (; distance > 0; distance--)
3520 tmp += step;
3521 switch (tmp->kind)
3523 /* FIXME: Ideally we'd like to "temporarily unwind" (some of) those
3524 unwind_protect, but the problem is that we don't know how to
3525 rewind them afterwards. */
3526 case SPECPDL_UNWIND:
3528 Lisp_Object oldarg = tmp->unwind.arg;
3529 if (tmp->unwind.func == set_buffer_if_live)
3530 tmp->unwind.arg = Fcurrent_buffer ();
3531 else if (tmp->unwind.func == save_excursion_restore)
3532 tmp->unwind.arg = save_excursion_save ();
3533 else
3534 break;
3535 tmp->unwind.func (oldarg);
3536 break;
3539 case SPECPDL_UNWIND_PTR:
3540 case SPECPDL_UNWIND_INT:
3541 case SPECPDL_UNWIND_VOID:
3542 case SPECPDL_BACKTRACE:
3543 break;
3544 case SPECPDL_LET:
3545 { /* If variable has a trivial value (no forwarding), we can
3546 just set it. No need to check for constant symbols here,
3547 since that was already done by specbind. */
3548 Lisp_Object sym = specpdl_symbol (tmp);
3549 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3551 Lisp_Object old_value = specpdl_old_value (tmp);
3552 set_specpdl_old_value (tmp, SYMBOL_VAL (XSYMBOL (sym)));
3553 SET_SYMBOL_VAL (XSYMBOL (sym), old_value);
3554 break;
3556 else
3557 { /* FALLTHROUGH!!
3558 NOTE: we only ever come here if make_local_foo was used for
3559 the first time on this var within this let. */
3562 case SPECPDL_LET_DEFAULT:
3564 Lisp_Object sym = specpdl_symbol (tmp);
3565 Lisp_Object old_value = specpdl_old_value (tmp);
3566 set_specpdl_old_value (tmp, Fdefault_value (sym));
3567 Fset_default (sym, old_value);
3569 break;
3570 case SPECPDL_LET_LOCAL:
3572 Lisp_Object symbol = specpdl_symbol (tmp);
3573 Lisp_Object where = specpdl_where (tmp);
3574 Lisp_Object old_value = specpdl_old_value (tmp);
3575 eassert (BUFFERP (where));
3577 /* If this was a local binding, reset the value in the appropriate
3578 buffer, but only if that buffer's binding still exists. */
3579 if (!NILP (Flocal_variable_p (symbol, where)))
3581 set_specpdl_old_value
3582 (tmp, Fbuffer_local_value (symbol, where));
3583 set_internal (symbol, old_value, where, 1);
3586 break;
3591 DEFUN ("backtrace-eval", Fbacktrace_eval, Sbacktrace_eval, 2, 3, NULL,
3592 doc: /* Evaluate EXP in the context of some activation frame.
3593 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3594 (Lisp_Object exp, Lisp_Object nframes, Lisp_Object base)
3596 union specbinding *pdl = get_backtrace_frame (nframes, base);
3597 ptrdiff_t count = SPECPDL_INDEX ();
3598 ptrdiff_t distance = specpdl_ptr - pdl;
3599 eassert (distance >= 0);
3601 if (!backtrace_p (pdl))
3602 error ("Activation frame not found!");
3604 backtrace_eval_unrewind (distance);
3605 record_unwind_protect_int (backtrace_eval_unrewind, -distance);
3607 /* Use eval_sub rather than Feval since the main motivation behind
3608 backtrace-eval is to be able to get/set the value of lexical variables
3609 from the debugger. */
3610 return unbind_to (count, eval_sub (exp));
3613 DEFUN ("backtrace--locals", Fbacktrace__locals, Sbacktrace__locals, 1, 2, NULL,
3614 doc: /* Return names and values of local variables of a stack frame.
3615 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3616 (Lisp_Object nframes, Lisp_Object base)
3618 union specbinding *frame = get_backtrace_frame (nframes, base);
3619 union specbinding *prevframe
3620 = get_backtrace_frame (make_number (XFASTINT (nframes) - 1), base);
3621 ptrdiff_t distance = specpdl_ptr - frame;
3622 Lisp_Object result = Qnil;
3623 eassert (distance >= 0);
3625 if (!backtrace_p (prevframe))
3626 error ("Activation frame not found!");
3627 if (!backtrace_p (frame))
3628 error ("Activation frame not found!");
3630 /* The specpdl entries normally contain the symbol being bound along with its
3631 `old_value', so it can be restored. The new value to which it is bound is
3632 available in one of two places: either in the current value of the
3633 variable (if it hasn't been rebound yet) or in the `old_value' slot of the
3634 next specpdl entry for it.
3635 `backtrace_eval_unrewind' happens to swap the role of `old_value'
3636 and "new value", so we abuse it here, to fetch the new value.
3637 It's ugly (we'd rather not modify global data) and a bit inefficient,
3638 but it does the job for now. */
3639 backtrace_eval_unrewind (distance);
3641 /* Grab values. */
3643 union specbinding *tmp = prevframe;
3644 for (; tmp > frame; tmp--)
3646 switch (tmp->kind)
3648 case SPECPDL_LET:
3649 case SPECPDL_LET_DEFAULT:
3650 case SPECPDL_LET_LOCAL:
3652 Lisp_Object sym = specpdl_symbol (tmp);
3653 Lisp_Object val = specpdl_old_value (tmp);
3654 if (EQ (sym, Qinternal_interpreter_environment))
3656 Lisp_Object env = val;
3657 for (; CONSP (env); env = XCDR (env))
3659 Lisp_Object binding = XCAR (env);
3660 if (CONSP (binding))
3661 result = Fcons (Fcons (XCAR (binding),
3662 XCDR (binding)),
3663 result);
3666 else
3667 result = Fcons (Fcons (sym, val), result);
3669 break;
3671 case SPECPDL_UNWIND:
3672 case SPECPDL_UNWIND_PTR:
3673 case SPECPDL_UNWIND_INT:
3674 case SPECPDL_UNWIND_VOID:
3675 case SPECPDL_BACKTRACE:
3676 break;
3678 default:
3679 emacs_abort ();
3684 /* Restore values from specpdl to original place. */
3685 backtrace_eval_unrewind (-distance);
3687 return result;
3691 void
3692 mark_specpdl (void)
3694 union specbinding *pdl;
3695 for (pdl = specpdl; pdl != specpdl_ptr; pdl++)
3697 switch (pdl->kind)
3699 case SPECPDL_UNWIND:
3700 mark_object (specpdl_arg (pdl));
3701 break;
3703 case SPECPDL_BACKTRACE:
3705 ptrdiff_t nargs = backtrace_nargs (pdl);
3706 mark_object (backtrace_function (pdl));
3707 if (nargs == UNEVALLED)
3708 nargs = 1;
3709 while (nargs--)
3710 mark_object (backtrace_args (pdl)[nargs]);
3712 break;
3714 case SPECPDL_LET_DEFAULT:
3715 case SPECPDL_LET_LOCAL:
3716 mark_object (specpdl_where (pdl));
3717 /* Fall through. */
3718 case SPECPDL_LET:
3719 mark_object (specpdl_symbol (pdl));
3720 mark_object (specpdl_old_value (pdl));
3721 break;
3723 case SPECPDL_UNWIND_PTR:
3724 case SPECPDL_UNWIND_INT:
3725 case SPECPDL_UNWIND_VOID:
3726 break;
3728 default:
3729 emacs_abort ();
3734 void
3735 get_backtrace (Lisp_Object array)
3737 union specbinding *pdl = backtrace_next (backtrace_top ());
3738 ptrdiff_t i = 0, asize = ASIZE (array);
3740 /* Copy the backtrace contents into working memory. */
3741 for (; i < asize; i++)
3743 if (backtrace_p (pdl))
3745 ASET (array, i, backtrace_function (pdl));
3746 pdl = backtrace_next (pdl);
3748 else
3749 ASET (array, i, Qnil);
3753 Lisp_Object backtrace_top_function (void)
3755 union specbinding *pdl = backtrace_top ();
3756 return (backtrace_p (pdl) ? backtrace_function (pdl) : Qnil);
3759 void
3760 syms_of_eval (void)
3762 DEFVAR_INT ("max-specpdl-size", max_specpdl_size,
3763 doc: /* Limit on number of Lisp variable bindings and `unwind-protect's.
3764 If Lisp code tries to increase the total number past this amount,
3765 an error is signaled.
3766 You can safely use a value considerably larger than the default value,
3767 if that proves inconveniently small. However, if you increase it too far,
3768 Emacs could run out of memory trying to make the stack bigger.
3769 Note that this limit may be silently increased by the debugger
3770 if `debug-on-error' or `debug-on-quit' is set. */);
3772 DEFVAR_INT ("max-lisp-eval-depth", max_lisp_eval_depth,
3773 doc: /* Limit on depth in `eval', `apply' and `funcall' before error.
3775 This limit serves to catch infinite recursions for you before they cause
3776 actual stack overflow in C, which would be fatal for Emacs.
3777 You can safely make it considerably larger than its default value,
3778 if that proves inconveniently small. However, if you increase it too far,
3779 Emacs could overflow the real C stack, and crash. */);
3781 DEFVAR_LISP ("quit-flag", Vquit_flag,
3782 doc: /* Non-nil causes `eval' to abort, unless `inhibit-quit' is non-nil.
3783 If the value is t, that means do an ordinary quit.
3784 If the value equals `throw-on-input', that means quit by throwing
3785 to the tag specified in `throw-on-input'; it's for handling `while-no-input'.
3786 Typing C-g sets `quit-flag' to t, regardless of `inhibit-quit',
3787 but `inhibit-quit' non-nil prevents anything from taking notice of that. */);
3788 Vquit_flag = Qnil;
3790 DEFVAR_LISP ("inhibit-quit", Vinhibit_quit,
3791 doc: /* Non-nil inhibits C-g quitting from happening immediately.
3792 Note that `quit-flag' will still be set by typing C-g,
3793 so a quit will be signaled as soon as `inhibit-quit' is nil.
3794 To prevent this happening, set `quit-flag' to nil
3795 before making `inhibit-quit' nil. */);
3796 Vinhibit_quit = Qnil;
3798 DEFSYM (Qsetq, "setq");
3799 DEFSYM (Qinhibit_quit, "inhibit-quit");
3800 DEFSYM (Qautoload, "autoload");
3801 DEFSYM (Qinhibit_debugger, "inhibit-debugger");
3802 DEFSYM (Qmacro, "macro");
3804 /* Note that the process handling also uses Qexit, but we don't want
3805 to staticpro it twice, so we just do it here. */
3806 DEFSYM (Qexit, "exit");
3808 DEFSYM (Qinteractive, "interactive");
3809 DEFSYM (Qcommandp, "commandp");
3810 DEFSYM (Qand_rest, "&rest");
3811 DEFSYM (Qand_optional, "&optional");
3812 DEFSYM (Qclosure, "closure");
3813 DEFSYM (QCdocumentation, ":documentation");
3814 DEFSYM (Qdebug, "debug");
3816 DEFVAR_LISP ("inhibit-debugger", Vinhibit_debugger,
3817 doc: /* Non-nil means never enter the debugger.
3818 Normally set while the debugger is already active, to avoid recursive
3819 invocations. */);
3820 Vinhibit_debugger = Qnil;
3822 DEFVAR_LISP ("debug-on-error", Vdebug_on_error,
3823 doc: /* Non-nil means enter debugger if an error is signaled.
3824 Does not apply to errors handled by `condition-case' or those
3825 matched by `debug-ignored-errors'.
3826 If the value is a list, an error only means to enter the debugger
3827 if one of its condition symbols appears in the list.
3828 When you evaluate an expression interactively, this variable
3829 is temporarily non-nil if `eval-expression-debug-on-error' is non-nil.
3830 The command `toggle-debug-on-error' toggles this.
3831 See also the variable `debug-on-quit' and `inhibit-debugger'. */);
3832 Vdebug_on_error = Qnil;
3834 DEFVAR_LISP ("debug-ignored-errors", Vdebug_ignored_errors,
3835 doc: /* List of errors for which the debugger should not be called.
3836 Each element may be a condition-name or a regexp that matches error messages.
3837 If any element applies to a given error, that error skips the debugger
3838 and just returns to top level.
3839 This overrides the variable `debug-on-error'.
3840 It does not apply to errors handled by `condition-case'. */);
3841 Vdebug_ignored_errors = Qnil;
3843 DEFVAR_BOOL ("debug-on-quit", debug_on_quit,
3844 doc: /* Non-nil means enter debugger if quit is signaled (C-g, for example).
3845 Does not apply if quit is handled by a `condition-case'. */);
3846 debug_on_quit = 0;
3848 DEFVAR_BOOL ("debug-on-next-call", debug_on_next_call,
3849 doc: /* Non-nil means enter debugger before next `eval', `apply' or `funcall'. */);
3851 DEFVAR_BOOL ("debugger-may-continue", debugger_may_continue,
3852 doc: /* Non-nil means debugger may continue execution.
3853 This is nil when the debugger is called under circumstances where it
3854 might not be safe to continue. */);
3855 debugger_may_continue = 1;
3857 DEFVAR_LISP ("debugger", Vdebugger,
3858 doc: /* Function to call to invoke debugger.
3859 If due to frame exit, args are `exit' and the value being returned;
3860 this function's value will be returned instead of that.
3861 If due to error, args are `error' and a list of the args to `signal'.
3862 If due to `apply' or `funcall' entry, one arg, `lambda'.
3863 If due to `eval' entry, one arg, t. */);
3864 Vdebugger = Qnil;
3866 DEFVAR_LISP ("signal-hook-function", Vsignal_hook_function,
3867 doc: /* If non-nil, this is a function for `signal' to call.
3868 It receives the same arguments that `signal' was given.
3869 The Edebug package uses this to regain control. */);
3870 Vsignal_hook_function = Qnil;
3872 DEFVAR_LISP ("debug-on-signal", Vdebug_on_signal,
3873 doc: /* Non-nil means call the debugger regardless of condition handlers.
3874 Note that `debug-on-error', `debug-on-quit' and friends
3875 still determine whether to handle the particular condition. */);
3876 Vdebug_on_signal = Qnil;
3878 /* When lexical binding is being used,
3879 Vinternal_interpreter_environment is non-nil, and contains an alist
3880 of lexically-bound variable, or (t), indicating an empty
3881 environment. The lisp name of this variable would be
3882 `internal-interpreter-environment' if it weren't hidden.
3883 Every element of this list can be either a cons (VAR . VAL)
3884 specifying a lexical binding, or a single symbol VAR indicating
3885 that this variable should use dynamic scoping. */
3886 DEFSYM (Qinternal_interpreter_environment,
3887 "internal-interpreter-environment");
3888 DEFVAR_LISP ("internal-interpreter-environment",
3889 Vinternal_interpreter_environment,
3890 doc: /* If non-nil, the current lexical environment of the lisp interpreter.
3891 When lexical binding is not being used, this variable is nil.
3892 A value of `(t)' indicates an empty environment, otherwise it is an
3893 alist of active lexical bindings. */);
3894 Vinternal_interpreter_environment = Qnil;
3895 /* Don't export this variable to Elisp, so no one can mess with it
3896 (Just imagine if someone makes it buffer-local). */
3897 Funintern (Qinternal_interpreter_environment, Qnil);
3899 Vrun_hooks = intern_c_string ("run-hooks");
3900 staticpro (&Vrun_hooks);
3902 staticpro (&Vautoload_queue);
3903 Vautoload_queue = Qnil;
3904 staticpro (&Vsignaling_function);
3905 Vsignaling_function = Qnil;
3907 inhibit_lisp_code = Qnil;
3909 defsubr (&Sor);
3910 defsubr (&Sand);
3911 defsubr (&Sif);
3912 defsubr (&Scond);
3913 defsubr (&Sprogn);
3914 defsubr (&Sprog1);
3915 defsubr (&Sprog2);
3916 defsubr (&Ssetq);
3917 defsubr (&Squote);
3918 defsubr (&Sfunction);
3919 defsubr (&Sdefault_toplevel_value);
3920 defsubr (&Sset_default_toplevel_value);
3921 defsubr (&Sdefvar);
3922 defsubr (&Sdefvaralias);
3923 defsubr (&Sdefconst);
3924 defsubr (&Smake_var_non_special);
3925 defsubr (&Slet);
3926 defsubr (&SletX);
3927 defsubr (&Swhile);
3928 defsubr (&Smacroexpand);
3929 defsubr (&Scatch);
3930 defsubr (&Sthrow);
3931 defsubr (&Sunwind_protect);
3932 defsubr (&Scondition_case);
3933 defsubr (&Ssignal);
3934 defsubr (&Scommandp);
3935 defsubr (&Sautoload);
3936 defsubr (&Sautoload_do_load);
3937 defsubr (&Seval);
3938 defsubr (&Sapply);
3939 defsubr (&Sfuncall);
3940 defsubr (&Sfunc_arity);
3941 defsubr (&Srun_hooks);
3942 defsubr (&Srun_hook_with_args);
3943 defsubr (&Srun_hook_with_args_until_success);
3944 defsubr (&Srun_hook_with_args_until_failure);
3945 defsubr (&Srun_hook_wrapped);
3946 defsubr (&Sfetch_bytecode);
3947 defsubr (&Sbacktrace_debug);
3948 defsubr (&Sbacktrace);
3949 defsubr (&Sbacktrace_frame);
3950 defsubr (&Sbacktrace_eval);
3951 defsubr (&Sbacktrace__locals);
3952 defsubr (&Sspecial_variable_p);
3953 defsubr (&Sfunctionp);