Merge from origin/emacs-25
[emacs.git] / src / eval.c
bloba9bad2491fae6885ef0b0485c10bc05e979038c0
1 /* Evaluator for GNU Emacs Lisp interpreter.
3 Copyright (C) 1985-1987, 1993-1995, 1999-2016 Free Software Foundation,
4 Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
23 #include <limits.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include "lisp.h"
27 #include "blockinput.h"
28 #include "commands.h"
29 #include "keyboard.h"
30 #include "dispextern.h"
31 #include "buffer.h"
33 /* Chain of condition and catch handlers currently in effect. */
35 struct handler *handlerlist;
37 /* Non-nil means record all fset's and provide's, to be undone
38 if the file being autoloaded is not fully loaded.
39 They are recorded by being consed onto the front of Vautoload_queue:
40 (FUN . ODEF) for a defun, (0 . OFEATURES) for a provide. */
42 Lisp_Object Vautoload_queue;
44 /* This holds either the symbol `run-hooks' or nil.
45 It is nil at an early stage of startup, and when Emacs
46 is shutting down. */
47 Lisp_Object Vrun_hooks;
49 /* Current number of specbindings allocated in specpdl, not counting
50 the dummy entry specpdl[-1]. */
52 ptrdiff_t specpdl_size;
54 /* Pointer to beginning of specpdl. A dummy entry specpdl[-1] exists
55 only so that its address can be taken. */
57 union specbinding *specpdl;
59 /* Pointer to first unused element in specpdl. */
61 union specbinding *specpdl_ptr;
63 /* Depth in Lisp evaluations and function calls. */
65 static EMACS_INT lisp_eval_depth;
67 /* The value of num_nonmacro_input_events as of the last time we
68 started to enter the debugger. If we decide to enter the debugger
69 again when this is still equal to num_nonmacro_input_events, then we
70 know that the debugger itself has an error, and we should just
71 signal the error instead of entering an infinite loop of debugger
72 invocations. */
74 static EMACS_INT when_entered_debugger;
76 /* The function from which the last `signal' was called. Set in
77 Fsignal. */
78 /* FIXME: We should probably get rid of this! */
79 Lisp_Object Vsignaling_function;
81 /* If non-nil, Lisp code must not be run since some part of Emacs is in
82 an inconsistent state. Currently unused. */
83 Lisp_Object inhibit_lisp_code;
85 /* These would ordinarily be static, but they need to be visible to GDB. */
86 bool backtrace_p (union specbinding *) EXTERNALLY_VISIBLE;
87 Lisp_Object *backtrace_args (union specbinding *) EXTERNALLY_VISIBLE;
88 Lisp_Object backtrace_function (union specbinding *) EXTERNALLY_VISIBLE;
89 union specbinding *backtrace_next (union specbinding *) EXTERNALLY_VISIBLE;
90 union specbinding *backtrace_top (void) EXTERNALLY_VISIBLE;
92 static Lisp_Object funcall_lambda (Lisp_Object, ptrdiff_t, Lisp_Object *);
93 static Lisp_Object apply_lambda (Lisp_Object, Lisp_Object, ptrdiff_t);
94 static Lisp_Object lambda_arity (Lisp_Object);
96 static Lisp_Object
97 specpdl_symbol (union specbinding *pdl)
99 eassert (pdl->kind >= SPECPDL_LET);
100 return pdl->let.symbol;
103 static Lisp_Object
104 specpdl_old_value (union specbinding *pdl)
106 eassert (pdl->kind >= SPECPDL_LET);
107 return pdl->let.old_value;
110 static void
111 set_specpdl_old_value (union specbinding *pdl, Lisp_Object val)
113 eassert (pdl->kind >= SPECPDL_LET);
114 pdl->let.old_value = val;
117 static Lisp_Object
118 specpdl_where (union specbinding *pdl)
120 eassert (pdl->kind > SPECPDL_LET);
121 return pdl->let.where;
124 static Lisp_Object
125 specpdl_arg (union specbinding *pdl)
127 eassert (pdl->kind == SPECPDL_UNWIND);
128 return pdl->unwind.arg;
131 Lisp_Object
132 backtrace_function (union specbinding *pdl)
134 eassert (pdl->kind == SPECPDL_BACKTRACE);
135 return pdl->bt.function;
138 static ptrdiff_t
139 backtrace_nargs (union specbinding *pdl)
141 eassert (pdl->kind == SPECPDL_BACKTRACE);
142 return pdl->bt.nargs;
145 Lisp_Object *
146 backtrace_args (union specbinding *pdl)
148 eassert (pdl->kind == SPECPDL_BACKTRACE);
149 return pdl->bt.args;
152 static bool
153 backtrace_debug_on_exit (union specbinding *pdl)
155 eassert (pdl->kind == SPECPDL_BACKTRACE);
156 return pdl->bt.debug_on_exit;
159 /* Functions to modify slots of backtrace records. */
161 static void
162 set_backtrace_args (union specbinding *pdl, Lisp_Object *args, ptrdiff_t nargs)
164 eassert (pdl->kind == SPECPDL_BACKTRACE);
165 pdl->bt.args = args;
166 pdl->bt.nargs = nargs;
169 static void
170 set_backtrace_debug_on_exit (union specbinding *pdl, bool doe)
172 eassert (pdl->kind == SPECPDL_BACKTRACE);
173 pdl->bt.debug_on_exit = doe;
176 /* Helper functions to scan the backtrace. */
178 bool
179 backtrace_p (union specbinding *pdl)
180 { return pdl >= specpdl; }
182 union specbinding *
183 backtrace_top (void)
185 union specbinding *pdl = specpdl_ptr - 1;
186 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
187 pdl--;
188 return pdl;
191 union specbinding *
192 backtrace_next (union specbinding *pdl)
194 pdl--;
195 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
196 pdl--;
197 return pdl;
200 /* Return a pointer to somewhere near the top of the C stack. */
201 void *
202 near_C_stack_top (void)
204 return backtrace_args (backtrace_top ());
207 void
208 init_eval_once (void)
210 enum { size = 50 };
211 union specbinding *pdlvec = xmalloc ((size + 1) * sizeof *specpdl);
212 specpdl_size = size;
213 specpdl = specpdl_ptr = pdlvec + 1;
214 /* Don't forget to update docs (lispref node "Local Variables"). */
215 max_specpdl_size = 1300; /* 1000 is not enough for CEDET's c-by.el. */
216 max_lisp_eval_depth = 800;
218 Vrun_hooks = Qnil;
221 static struct handler handlerlist_sentinel;
223 void
224 init_eval (void)
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 lisp_eval_depth = catch->lisp_eval_depth;
1140 sys_longjmp (catch->jmp, 1);
1143 DEFUN ("throw", Fthrow, Sthrow, 2, 2, 0,
1144 doc: /* Throw to the catch for TAG and return VALUE from it.
1145 Both TAG and VALUE are evalled. */
1146 attributes: noreturn)
1147 (register Lisp_Object tag, Lisp_Object value)
1149 struct handler *c;
1151 if (!NILP (tag))
1152 for (c = handlerlist; c; c = c->next)
1154 if (c->type == CATCHER_ALL)
1155 unwind_to_catch (c, Fcons (tag, value));
1156 if (c->type == CATCHER && EQ (c->tag_or_ch, tag))
1157 unwind_to_catch (c, value);
1159 xsignal2 (Qno_catch, tag, value);
1163 DEFUN ("unwind-protect", Funwind_protect, Sunwind_protect, 1, UNEVALLED, 0,
1164 doc: /* Do BODYFORM, protecting with UNWINDFORMS.
1165 If BODYFORM completes normally, its value is returned
1166 after executing the UNWINDFORMS.
1167 If BODYFORM exits nonlocally, the UNWINDFORMS are executed anyway.
1168 usage: (unwind-protect BODYFORM UNWINDFORMS...) */)
1169 (Lisp_Object args)
1171 Lisp_Object val;
1172 ptrdiff_t count = SPECPDL_INDEX ();
1174 record_unwind_protect (unwind_body, XCDR (args));
1175 val = eval_sub (XCAR (args));
1176 return unbind_to (count, val);
1179 DEFUN ("condition-case", Fcondition_case, Scondition_case, 2, UNEVALLED, 0,
1180 doc: /* Regain control when an error is signaled.
1181 Executes BODYFORM and returns its value if no error happens.
1182 Each element of HANDLERS looks like (CONDITION-NAME BODY...)
1183 where the BODY is made of Lisp expressions.
1185 A handler is applicable to an error
1186 if CONDITION-NAME is one of the error's condition names.
1187 If an error happens, the first applicable handler is run.
1189 The car of a handler may be a list of condition names instead of a
1190 single condition name; then it handles all of them. If the special
1191 condition name `debug' is present in this list, it allows another
1192 condition in the list to run the debugger if `debug-on-error' and the
1193 other usual mechanisms says it should (otherwise, `condition-case'
1194 suppresses the debugger).
1196 When a handler handles an error, control returns to the `condition-case'
1197 and it executes the handler's BODY...
1198 with VAR bound to (ERROR-SYMBOL . SIGNAL-DATA) from the error.
1199 \(If VAR is nil, the handler can't access that information.)
1200 Then the value of the last BODY form is returned from the `condition-case'
1201 expression.
1203 See also the function `signal' for more info.
1204 usage: (condition-case VAR BODYFORM &rest HANDLERS) */)
1205 (Lisp_Object args)
1207 Lisp_Object var = XCAR (args);
1208 Lisp_Object bodyform = XCAR (XCDR (args));
1209 Lisp_Object handlers = XCDR (XCDR (args));
1211 return internal_lisp_condition_case (var, bodyform, handlers);
1214 /* Like Fcondition_case, but the args are separate
1215 rather than passed in a list. Used by Fbyte_code. */
1217 Lisp_Object
1218 internal_lisp_condition_case (volatile Lisp_Object var, Lisp_Object bodyform,
1219 Lisp_Object handlers)
1221 Lisp_Object val;
1222 struct handler *oldhandlerlist = handlerlist;
1223 int clausenb = 0;
1225 CHECK_SYMBOL (var);
1227 for (val = handlers; CONSP (val); val = XCDR (val))
1229 Lisp_Object tem = XCAR (val);
1230 clausenb++;
1231 if (! (NILP (tem)
1232 || (CONSP (tem)
1233 && (SYMBOLP (XCAR (tem))
1234 || CONSP (XCAR (tem))))))
1235 error ("Invalid condition handler: %s",
1236 SDATA (Fprin1_to_string (tem, Qt)));
1239 { /* The first clause is the one that should be checked first, so it should
1240 be added to handlerlist last. So we build in `clauses' a table that
1241 contains `handlers' but in reverse order. SAFE_ALLOCA won't work
1242 here due to the setjmp, so impose a MAX_ALLOCA limit. */
1243 if (MAX_ALLOCA / word_size < clausenb)
1244 memory_full (SIZE_MAX);
1245 Lisp_Object *clauses = alloca (clausenb * sizeof *clauses);
1246 Lisp_Object *volatile clauses_volatile = clauses;
1247 int i = clausenb;
1248 for (val = handlers; CONSP (val); val = XCDR (val))
1249 clauses[--i] = XCAR (val);
1250 for (i = 0; i < clausenb; i++)
1252 Lisp_Object clause = clauses[i];
1253 Lisp_Object condition = CONSP (clause) ? XCAR (clause) : Qnil;
1254 if (!CONSP (condition))
1255 condition = Fcons (condition, Qnil);
1256 struct handler *c = push_handler (condition, CONDITION_CASE);
1257 if (sys_setjmp (c->jmp))
1259 ptrdiff_t count = SPECPDL_INDEX ();
1260 Lisp_Object val = handlerlist->val;
1261 Lisp_Object *chosen_clause = clauses_volatile;
1262 for (c = handlerlist->next; c != oldhandlerlist; c = c->next)
1263 chosen_clause++;
1264 handlerlist = oldhandlerlist;
1265 if (!NILP (var))
1267 if (!NILP (Vinternal_interpreter_environment))
1268 specbind (Qinternal_interpreter_environment,
1269 Fcons (Fcons (var, val),
1270 Vinternal_interpreter_environment));
1271 else
1272 specbind (var, val);
1274 val = Fprogn (XCDR (*chosen_clause));
1275 /* Note that this just undoes the binding of var; whoever
1276 longjumped to us unwound the stack to c.pdlcount before
1277 throwing. */
1278 if (!NILP (var))
1279 unbind_to (count, Qnil);
1280 return val;
1285 val = eval_sub (bodyform);
1286 handlerlist = oldhandlerlist;
1287 return val;
1290 /* Call the function BFUN with no arguments, catching errors within it
1291 according to HANDLERS. If there is an error, call HFUN with
1292 one argument which is the data that describes the error:
1293 (SIGNALNAME . DATA)
1295 HANDLERS can be a list of conditions to catch.
1296 If HANDLERS is Qt, catch all errors.
1297 If HANDLERS is Qerror, catch all errors
1298 but allow the debugger to run if that is enabled. */
1300 Lisp_Object
1301 internal_condition_case (Lisp_Object (*bfun) (void), Lisp_Object handlers,
1302 Lisp_Object (*hfun) (Lisp_Object))
1304 struct handler *c = push_handler (handlers, CONDITION_CASE);
1305 if (sys_setjmp (c->jmp))
1307 Lisp_Object val = handlerlist->val;
1308 clobbered_eassert (handlerlist == c);
1309 handlerlist = handlerlist->next;
1310 return hfun (val);
1312 else
1314 Lisp_Object val = bfun ();
1315 clobbered_eassert (handlerlist == c);
1316 handlerlist = handlerlist->next;
1317 return val;
1321 /* Like internal_condition_case but call BFUN with ARG as its argument. */
1323 Lisp_Object
1324 internal_condition_case_1 (Lisp_Object (*bfun) (Lisp_Object), Lisp_Object arg,
1325 Lisp_Object handlers,
1326 Lisp_Object (*hfun) (Lisp_Object))
1328 struct handler *c = push_handler (handlers, CONDITION_CASE);
1329 if (sys_setjmp (c->jmp))
1331 Lisp_Object val = handlerlist->val;
1332 clobbered_eassert (handlerlist == c);
1333 handlerlist = handlerlist->next;
1334 return hfun (val);
1336 else
1338 Lisp_Object val = bfun (arg);
1339 clobbered_eassert (handlerlist == c);
1340 handlerlist = handlerlist->next;
1341 return val;
1345 /* Like internal_condition_case_1 but call BFUN with ARG1 and ARG2 as
1346 its arguments. */
1348 Lisp_Object
1349 internal_condition_case_2 (Lisp_Object (*bfun) (Lisp_Object, Lisp_Object),
1350 Lisp_Object arg1,
1351 Lisp_Object arg2,
1352 Lisp_Object handlers,
1353 Lisp_Object (*hfun) (Lisp_Object))
1355 struct handler *c = push_handler (handlers, CONDITION_CASE);
1356 if (sys_setjmp (c->jmp))
1358 Lisp_Object val = handlerlist->val;
1359 clobbered_eassert (handlerlist == c);
1360 handlerlist = handlerlist->next;
1361 return hfun (val);
1363 else
1365 Lisp_Object val = bfun (arg1, arg2);
1366 clobbered_eassert (handlerlist == c);
1367 handlerlist = handlerlist->next;
1368 return val;
1372 /* Like internal_condition_case but call BFUN with NARGS as first,
1373 and ARGS as second argument. */
1375 Lisp_Object
1376 internal_condition_case_n (Lisp_Object (*bfun) (ptrdiff_t, Lisp_Object *),
1377 ptrdiff_t nargs,
1378 Lisp_Object *args,
1379 Lisp_Object handlers,
1380 Lisp_Object (*hfun) (Lisp_Object err,
1381 ptrdiff_t nargs,
1382 Lisp_Object *args))
1384 struct handler *c = push_handler (handlers, CONDITION_CASE);
1385 if (sys_setjmp (c->jmp))
1387 Lisp_Object val = handlerlist->val;
1388 clobbered_eassert (handlerlist == c);
1389 handlerlist = handlerlist->next;
1390 return hfun (val, nargs, args);
1392 else
1394 Lisp_Object val = bfun (nargs, args);
1395 clobbered_eassert (handlerlist == c);
1396 handlerlist = handlerlist->next;
1397 return val;
1401 struct handler *
1402 push_handler (Lisp_Object tag_ch_val, enum handlertype handlertype)
1404 struct handler *c = push_handler_nosignal (tag_ch_val, handlertype);
1405 if (!c)
1406 memory_full (sizeof *c);
1407 return c;
1410 struct handler *
1411 push_handler_nosignal (Lisp_Object tag_ch_val, enum handlertype handlertype)
1413 struct handler *c = handlerlist->nextfree;
1414 if (!c)
1416 c = malloc (sizeof *c);
1417 if (!c)
1418 return c;
1419 if (profiler_memory_running)
1420 malloc_probe (sizeof *c);
1421 c->nextfree = NULL;
1422 handlerlist->nextfree = c;
1424 c->type = handlertype;
1425 c->tag_or_ch = tag_ch_val;
1426 c->val = Qnil;
1427 c->next = handlerlist;
1428 c->lisp_eval_depth = lisp_eval_depth;
1429 c->pdlcount = SPECPDL_INDEX ();
1430 c->poll_suppress_count = poll_suppress_count;
1431 c->interrupt_input_blocked = interrupt_input_blocked;
1432 handlerlist = c;
1433 return c;
1437 static Lisp_Object signal_or_quit (Lisp_Object, Lisp_Object, bool);
1438 static Lisp_Object find_handler_clause (Lisp_Object, Lisp_Object);
1439 static bool maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig,
1440 Lisp_Object data);
1442 void
1443 process_quit_flag (void)
1445 Lisp_Object flag = Vquit_flag;
1446 Vquit_flag = Qnil;
1447 if (EQ (flag, Qkill_emacs))
1448 Fkill_emacs (Qnil);
1449 if (EQ (Vthrow_on_input, flag))
1450 Fthrow (Vthrow_on_input, Qt);
1451 quit ();
1454 DEFUN ("signal", Fsignal, Ssignal, 2, 2, 0,
1455 doc: /* Signal an error. Args are ERROR-SYMBOL and associated DATA.
1456 This function does not return.
1458 An error symbol is a symbol with an `error-conditions' property
1459 that is a list of condition names.
1460 A handler for any of those names will get to handle this signal.
1461 The symbol `error' should normally be one of them.
1463 DATA should be a list. Its elements are printed as part of the error message.
1464 See Info anchor `(elisp)Definition of signal' for some details on how this
1465 error message is constructed.
1466 If the signal is handled, DATA is made available to the handler.
1467 See also the function `condition-case'. */
1468 attributes: noreturn)
1469 (Lisp_Object error_symbol, Lisp_Object data)
1471 signal_or_quit (error_symbol, data, false);
1472 eassume (false);
1475 /* Quit, in response to a keyboard quit request. */
1476 Lisp_Object
1477 quit (void)
1479 return signal_or_quit (Qquit, Qnil, true);
1482 /* Signal an error, or quit. ERROR_SYMBOL and DATA are as with Fsignal.
1483 If KEYBOARD_QUIT, this is a quit; ERROR_SYMBOL should be
1484 Qquit and DATA should be Qnil, and this function may return.
1485 Otherwise this function is like Fsignal and does not return. */
1487 static Lisp_Object
1488 signal_or_quit (Lisp_Object error_symbol, Lisp_Object data, bool keyboard_quit)
1490 /* When memory is full, ERROR-SYMBOL is nil,
1491 and DATA is (REAL-ERROR-SYMBOL . REAL-DATA).
1492 That is a special case--don't do this in other situations. */
1493 Lisp_Object conditions;
1494 Lisp_Object string;
1495 Lisp_Object real_error_symbol
1496 = (NILP (error_symbol) ? Fcar (data) : error_symbol);
1497 register Lisp_Object clause = Qnil;
1498 struct handler *h;
1500 immediate_quit = 0;
1501 if (gc_in_progress || waiting_for_input)
1502 emacs_abort ();
1504 #if 0 /* rms: I don't know why this was here,
1505 but it is surely wrong for an error that is handled. */
1506 #ifdef HAVE_WINDOW_SYSTEM
1507 if (display_hourglass_p)
1508 cancel_hourglass ();
1509 #endif
1510 #endif
1512 /* This hook is used by edebug. */
1513 if (! NILP (Vsignal_hook_function)
1514 && ! NILP (error_symbol))
1516 /* Edebug takes care of restoring these variables when it exits. */
1517 if (lisp_eval_depth + 20 > max_lisp_eval_depth)
1518 max_lisp_eval_depth = lisp_eval_depth + 20;
1520 if (SPECPDL_INDEX () + 40 > max_specpdl_size)
1521 max_specpdl_size = SPECPDL_INDEX () + 40;
1523 call2 (Vsignal_hook_function, error_symbol, data);
1526 conditions = Fget (real_error_symbol, Qerror_conditions);
1528 /* Remember from where signal was called. Skip over the frame for
1529 `signal' itself. If a frame for `error' follows, skip that,
1530 too. Don't do this when ERROR_SYMBOL is nil, because that
1531 is a memory-full error. */
1532 Vsignaling_function = Qnil;
1533 if (!NILP (error_symbol))
1535 union specbinding *pdl = backtrace_next (backtrace_top ());
1536 if (backtrace_p (pdl) && EQ (backtrace_function (pdl), Qerror))
1537 pdl = backtrace_next (pdl);
1538 if (backtrace_p (pdl))
1539 Vsignaling_function = backtrace_function (pdl);
1542 for (h = handlerlist; h; h = h->next)
1544 if (h->type != CONDITION_CASE)
1545 continue;
1546 clause = find_handler_clause (h->tag_or_ch, conditions);
1547 if (!NILP (clause))
1548 break;
1551 if (/* Don't run the debugger for a memory-full error.
1552 (There is no room in memory to do that!) */
1553 !NILP (error_symbol)
1554 && (!NILP (Vdebug_on_signal)
1555 /* If no handler is present now, try to run the debugger. */
1556 || NILP (clause)
1557 /* A `debug' symbol in the handler list disables the normal
1558 suppression of the debugger. */
1559 || (CONSP (clause) && !NILP (Fmemq (Qdebug, clause)))
1560 /* Special handler that means "print a message and run debugger
1561 if requested". */
1562 || EQ (h->tag_or_ch, Qerror)))
1564 bool debugger_called
1565 = maybe_call_debugger (conditions, error_symbol, data);
1566 /* We can't return values to code which signaled an error, but we
1567 can continue code which has signaled a quit. */
1568 if (keyboard_quit && debugger_called && EQ (real_error_symbol, Qquit))
1569 return Qnil;
1572 if (!NILP (clause))
1574 Lisp_Object unwind_data
1575 = (NILP (error_symbol) ? data : Fcons (error_symbol, data));
1577 unwind_to_catch (h, unwind_data);
1579 else
1581 if (handlerlist != &handlerlist_sentinel)
1582 /* FIXME: This will come right back here if there's no `top-level'
1583 catcher. A better solution would be to abort here, and instead
1584 add a catch-all condition handler so we never come here. */
1585 Fthrow (Qtop_level, Qt);
1588 if (! NILP (error_symbol))
1589 data = Fcons (error_symbol, data);
1591 string = Ferror_message_string (data);
1592 fatal ("%s", SDATA (string));
1595 /* Like xsignal, but takes 0, 1, 2, or 3 args instead of a list. */
1597 void
1598 xsignal0 (Lisp_Object error_symbol)
1600 xsignal (error_symbol, Qnil);
1603 void
1604 xsignal1 (Lisp_Object error_symbol, Lisp_Object arg)
1606 xsignal (error_symbol, list1 (arg));
1609 void
1610 xsignal2 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2)
1612 xsignal (error_symbol, list2 (arg1, arg2));
1615 void
1616 xsignal3 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
1618 xsignal (error_symbol, list3 (arg1, arg2, arg3));
1621 /* Signal `error' with message S, and additional arg ARG.
1622 If ARG is not a genuine list, make it a one-element list. */
1624 void
1625 signal_error (const char *s, Lisp_Object arg)
1627 Lisp_Object tortoise, hare;
1629 hare = tortoise = arg;
1630 while (CONSP (hare))
1632 hare = XCDR (hare);
1633 if (!CONSP (hare))
1634 break;
1636 hare = XCDR (hare);
1637 tortoise = XCDR (tortoise);
1639 if (EQ (hare, tortoise))
1640 break;
1643 if (!NILP (hare))
1644 arg = list1 (arg);
1646 xsignal (Qerror, Fcons (build_string (s), arg));
1650 /* Return true if LIST is a non-nil atom or
1651 a list containing one of CONDITIONS. */
1653 static bool
1654 wants_debugger (Lisp_Object list, Lisp_Object conditions)
1656 if (NILP (list))
1657 return 0;
1658 if (! CONSP (list))
1659 return 1;
1661 while (CONSP (conditions))
1663 Lisp_Object this, tail;
1664 this = XCAR (conditions);
1665 for (tail = list; CONSP (tail); tail = XCDR (tail))
1666 if (EQ (XCAR (tail), this))
1667 return 1;
1668 conditions = XCDR (conditions);
1670 return 0;
1673 /* Return true if an error with condition-symbols CONDITIONS,
1674 and described by SIGNAL-DATA, should skip the debugger
1675 according to debugger-ignored-errors. */
1677 static bool
1678 skip_debugger (Lisp_Object conditions, Lisp_Object data)
1680 Lisp_Object tail;
1681 bool first_string = 1;
1682 Lisp_Object error_message;
1684 error_message = Qnil;
1685 for (tail = Vdebug_ignored_errors; CONSP (tail); tail = XCDR (tail))
1687 if (STRINGP (XCAR (tail)))
1689 if (first_string)
1691 error_message = Ferror_message_string (data);
1692 first_string = 0;
1695 if (fast_string_match (XCAR (tail), error_message) >= 0)
1696 return 1;
1698 else
1700 Lisp_Object contail;
1702 for (contail = conditions; CONSP (contail); contail = XCDR (contail))
1703 if (EQ (XCAR (tail), XCAR (contail)))
1704 return 1;
1708 return 0;
1711 /* Call the debugger if calling it is currently enabled for CONDITIONS.
1712 SIG and DATA describe the signal. There are two ways to pass them:
1713 = SIG is the error symbol, and DATA is the rest of the data.
1714 = SIG is nil, and DATA is (SYMBOL . REST-OF-DATA).
1715 This is for memory-full errors only. */
1716 static bool
1717 maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig, Lisp_Object data)
1719 Lisp_Object combined_data;
1721 combined_data = Fcons (sig, data);
1723 if (
1724 /* Don't try to run the debugger with interrupts blocked.
1725 The editing loop would return anyway. */
1726 ! input_blocked_p ()
1727 && NILP (Vinhibit_debugger)
1728 /* Does user want to enter debugger for this kind of error? */
1729 && (EQ (sig, Qquit)
1730 ? debug_on_quit
1731 : wants_debugger (Vdebug_on_error, conditions))
1732 && ! skip_debugger (conditions, combined_data)
1733 /* RMS: What's this for? */
1734 && when_entered_debugger < num_nonmacro_input_events)
1736 call_debugger (list2 (Qerror, combined_data));
1737 return 1;
1740 return 0;
1743 static Lisp_Object
1744 find_handler_clause (Lisp_Object handlers, Lisp_Object conditions)
1746 register Lisp_Object h;
1748 /* t is used by handlers for all conditions, set up by C code. */
1749 if (EQ (handlers, Qt))
1750 return Qt;
1752 /* error is used similarly, but means print an error message
1753 and run the debugger if that is enabled. */
1754 if (EQ (handlers, Qerror))
1755 return Qt;
1757 for (h = handlers; CONSP (h); h = XCDR (h))
1759 Lisp_Object handler = XCAR (h);
1760 if (!NILP (Fmemq (handler, conditions)))
1761 return handlers;
1764 return Qnil;
1768 /* Format and return a string; called like vprintf. */
1769 Lisp_Object
1770 vformat_string (const char *m, va_list ap)
1772 char buf[4000];
1773 ptrdiff_t size = sizeof buf;
1774 ptrdiff_t size_max = STRING_BYTES_BOUND + 1;
1775 char *buffer = buf;
1776 ptrdiff_t used;
1777 Lisp_Object string;
1779 used = evxprintf (&buffer, &size, buf, size_max, m, ap);
1780 string = make_string (buffer, used);
1781 if (buffer != buf)
1782 xfree (buffer);
1784 return string;
1787 /* Dump an error message; called like vprintf. */
1788 void
1789 verror (const char *m, va_list ap)
1791 xsignal1 (Qerror, vformat_string (m, ap));
1795 /* Dump an error message; called like printf. */
1797 /* VARARGS 1 */
1798 void
1799 error (const char *m, ...)
1801 va_list ap;
1802 va_start (ap, m);
1803 verror (m, ap);
1806 DEFUN ("commandp", Fcommandp, Scommandp, 1, 2, 0,
1807 doc: /* Non-nil if FUNCTION makes provisions for interactive calling.
1808 This means it contains a description for how to read arguments to give it.
1809 The value is nil for an invalid function or a symbol with no function
1810 definition.
1812 Interactively callable functions include strings and vectors (treated
1813 as keyboard macros), lambda-expressions that contain a top-level call
1814 to `interactive', autoload definitions made by `autoload' with non-nil
1815 fourth argument, and some of the built-in functions of Lisp.
1817 Also, a symbol satisfies `commandp' if its function definition does so.
1819 If the optional argument FOR-CALL-INTERACTIVELY is non-nil,
1820 then strings and vectors are not accepted. */)
1821 (Lisp_Object function, Lisp_Object for_call_interactively)
1823 register Lisp_Object fun;
1824 register Lisp_Object funcar;
1825 Lisp_Object if_prop = Qnil;
1827 fun = function;
1829 fun = indirect_function (fun); /* Check cycles. */
1830 if (NILP (fun))
1831 return Qnil;
1833 /* Check an `interactive-form' property if present, analogous to the
1834 function-documentation property. */
1835 fun = function;
1836 while (SYMBOLP (fun))
1838 Lisp_Object tmp = Fget (fun, Qinteractive_form);
1839 if (!NILP (tmp))
1840 if_prop = Qt;
1841 fun = Fsymbol_function (fun);
1844 /* Emacs primitives are interactive if their DEFUN specifies an
1845 interactive spec. */
1846 if (SUBRP (fun))
1847 return XSUBR (fun)->intspec ? Qt : if_prop;
1849 /* Bytecode objects are interactive if they are long enough to
1850 have an element whose index is COMPILED_INTERACTIVE, which is
1851 where the interactive spec is stored. */
1852 else if (COMPILEDP (fun))
1853 return ((ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK) > COMPILED_INTERACTIVE
1854 ? Qt : if_prop);
1856 /* Strings and vectors are keyboard macros. */
1857 if (STRINGP (fun) || VECTORP (fun))
1858 return (NILP (for_call_interactively) ? Qt : Qnil);
1860 /* Lists may represent commands. */
1861 if (!CONSP (fun))
1862 return Qnil;
1863 funcar = XCAR (fun);
1864 if (EQ (funcar, Qclosure))
1865 return (!NILP (Fassq (Qinteractive, Fcdr (Fcdr (XCDR (fun)))))
1866 ? Qt : if_prop);
1867 else if (EQ (funcar, Qlambda))
1868 return !NILP (Fassq (Qinteractive, Fcdr (XCDR (fun)))) ? Qt : if_prop;
1869 else if (EQ (funcar, Qautoload))
1870 return !NILP (Fcar (Fcdr (Fcdr (XCDR (fun))))) ? Qt : if_prop;
1871 else
1872 return Qnil;
1875 DEFUN ("autoload", Fautoload, Sautoload, 2, 5, 0,
1876 doc: /* Define FUNCTION to autoload from FILE.
1877 FUNCTION is a symbol; FILE is a file name string to pass to `load'.
1878 Third arg DOCSTRING is documentation for the function.
1879 Fourth arg INTERACTIVE if non-nil says function can be called interactively.
1880 Fifth arg TYPE indicates the type of the object:
1881 nil or omitted says FUNCTION is a function,
1882 `keymap' says FUNCTION is really a keymap, and
1883 `macro' or t says FUNCTION is really a macro.
1884 Third through fifth args give info about the real definition.
1885 They default to nil.
1886 If FUNCTION is already defined other than as an autoload,
1887 this does nothing and returns nil. */)
1888 (Lisp_Object function, Lisp_Object file, Lisp_Object docstring, Lisp_Object interactive, Lisp_Object type)
1890 CHECK_SYMBOL (function);
1891 CHECK_STRING (file);
1893 /* If function is defined and not as an autoload, don't override. */
1894 if (!NILP (XSYMBOL (function)->function)
1895 && !AUTOLOADP (XSYMBOL (function)->function))
1896 return Qnil;
1898 if (!NILP (Vpurify_flag) && EQ (docstring, make_number (0)))
1899 /* `read1' in lread.c has found the docstring starting with "\
1900 and assumed the docstring will be provided by Snarf-documentation, so it
1901 passed us 0 instead. But that leads to accidental sharing in purecopy's
1902 hash-consing, so we use a (hopefully) unique integer instead. */
1903 docstring = make_number (XHASH (function));
1904 return Fdefalias (function,
1905 list5 (Qautoload, file, docstring, interactive, type),
1906 Qnil);
1909 void
1910 un_autoload (Lisp_Object oldqueue)
1912 Lisp_Object queue, first, second;
1914 /* Queue to unwind is current value of Vautoload_queue.
1915 oldqueue is the shadowed value to leave in Vautoload_queue. */
1916 queue = Vautoload_queue;
1917 Vautoload_queue = oldqueue;
1918 while (CONSP (queue))
1920 first = XCAR (queue);
1921 second = Fcdr (first);
1922 first = Fcar (first);
1923 if (EQ (first, make_number (0)))
1924 Vfeatures = second;
1925 else
1926 Ffset (first, second);
1927 queue = XCDR (queue);
1931 /* Load an autoloaded function.
1932 FUNNAME is the symbol which is the function's name.
1933 FUNDEF is the autoload definition (a list). */
1935 DEFUN ("autoload-do-load", Fautoload_do_load, Sautoload_do_load, 1, 3, 0,
1936 doc: /* Load FUNDEF which should be an autoload.
1937 If non-nil, FUNNAME should be the symbol whose function value is FUNDEF,
1938 in which case the function returns the new autoloaded function value.
1939 If equal to `macro', MACRO-ONLY specifies that FUNDEF should only be loaded if
1940 it defines a macro. */)
1941 (Lisp_Object fundef, Lisp_Object funname, Lisp_Object macro_only)
1943 ptrdiff_t count = SPECPDL_INDEX ();
1945 if (!CONSP (fundef) || !EQ (Qautoload, XCAR (fundef)))
1946 return fundef;
1948 if (EQ (macro_only, Qmacro))
1950 Lisp_Object kind = Fnth (make_number (4), fundef);
1951 if (! (EQ (kind, Qt) || EQ (kind, Qmacro)))
1952 return fundef;
1955 /* This is to make sure that loadup.el gives a clear picture
1956 of what files are preloaded and when. */
1957 if (! NILP (Vpurify_flag))
1958 error ("Attempt to autoload %s while preparing to dump",
1959 SDATA (SYMBOL_NAME (funname)));
1961 CHECK_SYMBOL (funname);
1963 /* Preserve the match data. */
1964 record_unwind_save_match_data ();
1966 /* If autoloading gets an error (which includes the error of failing
1967 to define the function being called), we use Vautoload_queue
1968 to undo function definitions and `provide' calls made by
1969 the function. We do this in the specific case of autoloading
1970 because autoloading is not an explicit request "load this file",
1971 but rather a request to "call this function".
1973 The value saved here is to be restored into Vautoload_queue. */
1974 record_unwind_protect (un_autoload, Vautoload_queue);
1975 Vautoload_queue = Qt;
1976 /* If `macro_only', assume this autoload to be a "best-effort",
1977 so don't signal an error if autoloading fails. */
1978 Fload (Fcar (Fcdr (fundef)), macro_only, Qt, Qnil, Qt);
1980 /* Once loading finishes, don't undo it. */
1981 Vautoload_queue = Qt;
1982 unbind_to (count, Qnil);
1984 if (NILP (funname))
1985 return Qnil;
1986 else
1988 Lisp_Object fun = Findirect_function (funname, Qnil);
1990 if (!NILP (Fequal (fun, fundef)))
1991 error ("Autoloading failed to define function %s",
1992 SDATA (SYMBOL_NAME (funname)));
1993 else
1994 return fun;
1999 DEFUN ("eval", Feval, Seval, 1, 2, 0,
2000 doc: /* Evaluate FORM and return its value.
2001 If LEXICAL is t, evaluate using lexical scoping.
2002 LEXICAL can also be an actual lexical environment, in the form of an
2003 alist mapping symbols to their value. */)
2004 (Lisp_Object form, Lisp_Object lexical)
2006 ptrdiff_t count = SPECPDL_INDEX ();
2007 specbind (Qinternal_interpreter_environment,
2008 CONSP (lexical) || NILP (lexical) ? lexical : list1 (Qt));
2009 return unbind_to (count, eval_sub (form));
2012 /* Grow the specpdl stack by one entry.
2013 The caller should have already initialized the entry.
2014 Signal an error on stack overflow.
2016 Make sure that there is always one unused entry past the top of the
2017 stack, so that the just-initialized entry is safely unwound if
2018 memory exhausted and an error is signaled here. Also, allocate a
2019 never-used entry just before the bottom of the stack; sometimes its
2020 address is taken. */
2022 static void
2023 grow_specpdl (void)
2025 specpdl_ptr++;
2027 if (specpdl_ptr == specpdl + specpdl_size)
2029 ptrdiff_t count = SPECPDL_INDEX ();
2030 ptrdiff_t max_size = min (max_specpdl_size, PTRDIFF_MAX - 1000);
2031 union specbinding *pdlvec = specpdl - 1;
2032 ptrdiff_t pdlvecsize = specpdl_size + 1;
2033 if (max_size <= specpdl_size)
2035 if (max_specpdl_size < 400)
2036 max_size = max_specpdl_size = 400;
2037 if (max_size <= specpdl_size)
2038 signal_error ("Variable binding depth exceeds max-specpdl-size",
2039 Qnil);
2041 pdlvec = xpalloc (pdlvec, &pdlvecsize, 1, max_size + 1, sizeof *specpdl);
2042 specpdl = pdlvec + 1;
2043 specpdl_size = pdlvecsize - 1;
2044 specpdl_ptr = specpdl + count;
2048 ptrdiff_t
2049 record_in_backtrace (Lisp_Object function, Lisp_Object *args, ptrdiff_t nargs)
2051 ptrdiff_t count = SPECPDL_INDEX ();
2053 eassert (nargs >= UNEVALLED);
2054 specpdl_ptr->bt.kind = SPECPDL_BACKTRACE;
2055 specpdl_ptr->bt.debug_on_exit = false;
2056 specpdl_ptr->bt.function = function;
2057 specpdl_ptr->bt.args = args;
2058 specpdl_ptr->bt.nargs = nargs;
2059 grow_specpdl ();
2061 return count;
2064 /* Eval a sub-expression of the current expression (i.e. in the same
2065 lexical scope). */
2066 Lisp_Object
2067 eval_sub (Lisp_Object form)
2069 Lisp_Object fun, val, original_fun, original_args;
2070 Lisp_Object funcar;
2071 ptrdiff_t count;
2073 /* Declare here, as this array may be accessed by call_debugger near
2074 the end of this function. See Bug#21245. */
2075 Lisp_Object argvals[8];
2077 if (SYMBOLP (form))
2079 /* Look up its binding in the lexical environment.
2080 We do not pay attention to the declared_special flag here, since we
2081 already did that when let-binding the variable. */
2082 Lisp_Object lex_binding
2083 = !NILP (Vinternal_interpreter_environment) /* Mere optimization! */
2084 ? Fassq (form, Vinternal_interpreter_environment)
2085 : Qnil;
2086 if (CONSP (lex_binding))
2087 return XCDR (lex_binding);
2088 else
2089 return Fsymbol_value (form);
2092 if (!CONSP (form))
2093 return form;
2095 QUIT;
2097 maybe_gc ();
2099 if (++lisp_eval_depth > max_lisp_eval_depth)
2101 if (max_lisp_eval_depth < 100)
2102 max_lisp_eval_depth = 100;
2103 if (lisp_eval_depth > max_lisp_eval_depth)
2104 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2107 original_fun = XCAR (form);
2108 original_args = XCDR (form);
2110 /* This also protects them from gc. */
2111 count = record_in_backtrace (original_fun, &original_args, UNEVALLED);
2113 if (debug_on_next_call)
2114 do_debug_on_call (Qt, count);
2116 /* At this point, only original_fun and original_args
2117 have values that will be used below. */
2118 retry:
2120 /* Optimize for no indirection. */
2121 fun = original_fun;
2122 if (!SYMBOLP (fun))
2123 fun = Ffunction (Fcons (fun, Qnil));
2124 else if (!NILP (fun) && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2125 fun = indirect_function (fun);
2127 if (SUBRP (fun))
2129 Lisp_Object args_left = original_args;
2130 Lisp_Object numargs = Flength (args_left);
2132 check_cons_list ();
2134 if (XINT (numargs) < XSUBR (fun)->min_args
2135 || (XSUBR (fun)->max_args >= 0
2136 && XSUBR (fun)->max_args < XINT (numargs)))
2137 xsignal2 (Qwrong_number_of_arguments, original_fun, numargs);
2139 else if (XSUBR (fun)->max_args == UNEVALLED)
2140 val = (XSUBR (fun)->function.aUNEVALLED) (args_left);
2141 else if (XSUBR (fun)->max_args == MANY)
2143 /* Pass a vector of evaluated arguments. */
2144 Lisp_Object *vals;
2145 ptrdiff_t argnum = 0;
2146 USE_SAFE_ALLOCA;
2148 SAFE_ALLOCA_LISP (vals, XINT (numargs));
2150 while (!NILP (args_left))
2152 vals[argnum++] = eval_sub (Fcar (args_left));
2153 args_left = Fcdr (args_left);
2156 set_backtrace_args (specpdl + count, vals, XINT (numargs));
2158 val = (XSUBR (fun)->function.aMANY) (XINT (numargs), vals);
2160 check_cons_list ();
2161 lisp_eval_depth--;
2162 /* Do the debug-on-exit now, while VALS still exists. */
2163 if (backtrace_debug_on_exit (specpdl + count))
2164 val = call_debugger (list2 (Qexit, val));
2165 SAFE_FREE ();
2166 specpdl_ptr--;
2167 return val;
2169 else
2171 int i, maxargs = XSUBR (fun)->max_args;
2173 for (i = 0; i < maxargs; i++)
2175 argvals[i] = eval_sub (Fcar (args_left));
2176 args_left = Fcdr (args_left);
2179 set_backtrace_args (specpdl + count, argvals, XINT (numargs));
2181 switch (i)
2183 case 0:
2184 val = (XSUBR (fun)->function.a0 ());
2185 break;
2186 case 1:
2187 val = (XSUBR (fun)->function.a1 (argvals[0]));
2188 break;
2189 case 2:
2190 val = (XSUBR (fun)->function.a2 (argvals[0], argvals[1]));
2191 break;
2192 case 3:
2193 val = (XSUBR (fun)->function.a3
2194 (argvals[0], argvals[1], argvals[2]));
2195 break;
2196 case 4:
2197 val = (XSUBR (fun)->function.a4
2198 (argvals[0], argvals[1], argvals[2], argvals[3]));
2199 break;
2200 case 5:
2201 val = (XSUBR (fun)->function.a5
2202 (argvals[0], argvals[1], argvals[2], argvals[3],
2203 argvals[4]));
2204 break;
2205 case 6:
2206 val = (XSUBR (fun)->function.a6
2207 (argvals[0], argvals[1], argvals[2], argvals[3],
2208 argvals[4], argvals[5]));
2209 break;
2210 case 7:
2211 val = (XSUBR (fun)->function.a7
2212 (argvals[0], argvals[1], argvals[2], argvals[3],
2213 argvals[4], argvals[5], argvals[6]));
2214 break;
2216 case 8:
2217 val = (XSUBR (fun)->function.a8
2218 (argvals[0], argvals[1], argvals[2], argvals[3],
2219 argvals[4], argvals[5], argvals[6], argvals[7]));
2220 break;
2222 default:
2223 /* Someone has created a subr that takes more arguments than
2224 is supported by this code. We need to either rewrite the
2225 subr to use a different argument protocol, or add more
2226 cases to this switch. */
2227 emacs_abort ();
2231 else if (COMPILEDP (fun))
2232 return apply_lambda (fun, original_args, count);
2233 else
2235 if (NILP (fun))
2236 xsignal1 (Qvoid_function, original_fun);
2237 if (!CONSP (fun))
2238 xsignal1 (Qinvalid_function, original_fun);
2239 funcar = XCAR (fun);
2240 if (!SYMBOLP (funcar))
2241 xsignal1 (Qinvalid_function, original_fun);
2242 if (EQ (funcar, Qautoload))
2244 Fautoload_do_load (fun, original_fun, Qnil);
2245 goto retry;
2247 if (EQ (funcar, Qmacro))
2249 ptrdiff_t count1 = SPECPDL_INDEX ();
2250 Lisp_Object exp;
2251 /* Bind lexical-binding during expansion of the macro, so the
2252 macro can know reliably if the code it outputs will be
2253 interpreted using lexical-binding or not. */
2254 specbind (Qlexical_binding,
2255 NILP (Vinternal_interpreter_environment) ? Qnil : Qt);
2256 exp = apply1 (Fcdr (fun), original_args);
2257 unbind_to (count1, Qnil);
2258 val = eval_sub (exp);
2260 else if (EQ (funcar, Qlambda)
2261 || EQ (funcar, Qclosure))
2262 return apply_lambda (fun, original_args, count);
2263 else
2264 xsignal1 (Qinvalid_function, original_fun);
2266 check_cons_list ();
2268 lisp_eval_depth--;
2269 if (backtrace_debug_on_exit (specpdl + count))
2270 val = call_debugger (list2 (Qexit, val));
2271 specpdl_ptr--;
2273 return val;
2276 DEFUN ("apply", Fapply, Sapply, 1, MANY, 0,
2277 doc: /* Call FUNCTION with our remaining args, using our last arg as list of args.
2278 Then return the value FUNCTION returns.
2279 Thus, (apply \\='+ 1 2 \\='(3 4)) returns 10.
2280 usage: (apply FUNCTION &rest ARGUMENTS) */)
2281 (ptrdiff_t nargs, Lisp_Object *args)
2283 ptrdiff_t i, numargs, funcall_nargs;
2284 register Lisp_Object *funcall_args = NULL;
2285 register Lisp_Object spread_arg = args[nargs - 1];
2286 Lisp_Object fun = args[0];
2287 Lisp_Object retval;
2288 USE_SAFE_ALLOCA;
2290 CHECK_LIST (spread_arg);
2292 numargs = XINT (Flength (spread_arg));
2294 if (numargs == 0)
2295 return Ffuncall (nargs - 1, args);
2296 else if (numargs == 1)
2298 args [nargs - 1] = XCAR (spread_arg);
2299 return Ffuncall (nargs, args);
2302 numargs += nargs - 2;
2304 /* Optimize for no indirection. */
2305 if (SYMBOLP (fun) && !NILP (fun)
2306 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2308 fun = indirect_function (fun);
2309 if (NILP (fun))
2310 /* Let funcall get the error. */
2311 fun = args[0];
2314 if (SUBRP (fun) && XSUBR (fun)->max_args > numargs
2315 /* Don't hide an error by adding missing arguments. */
2316 && numargs >= XSUBR (fun)->min_args)
2318 /* Avoid making funcall cons up a yet another new vector of arguments
2319 by explicitly supplying nil's for optional values. */
2320 SAFE_ALLOCA_LISP (funcall_args, 1 + XSUBR (fun)->max_args);
2321 memclear (funcall_args + numargs + 1,
2322 (XSUBR (fun)->max_args - numargs) * word_size);
2323 funcall_nargs = 1 + XSUBR (fun)->max_args;
2325 else
2326 { /* We add 1 to numargs because funcall_args includes the
2327 function itself as well as its arguments. */
2328 SAFE_ALLOCA_LISP (funcall_args, 1 + numargs);
2329 funcall_nargs = 1 + numargs;
2332 memcpy (funcall_args, args, nargs * word_size);
2333 /* Spread the last arg we got. Its first element goes in
2334 the slot that it used to occupy, hence this value of I. */
2335 i = nargs - 1;
2336 while (!NILP (spread_arg))
2338 funcall_args [i++] = XCAR (spread_arg);
2339 spread_arg = XCDR (spread_arg);
2342 retval = Ffuncall (funcall_nargs, funcall_args);
2344 SAFE_FREE ();
2345 return retval;
2348 /* Run hook variables in various ways. */
2350 static Lisp_Object
2351 funcall_nil (ptrdiff_t nargs, Lisp_Object *args)
2353 Ffuncall (nargs, args);
2354 return Qnil;
2357 DEFUN ("run-hooks", Frun_hooks, Srun_hooks, 0, MANY, 0,
2358 doc: /* Run each hook in HOOKS.
2359 Each argument should be a symbol, a hook variable.
2360 These symbols are processed in the order specified.
2361 If a hook symbol has a non-nil value, that value may be a function
2362 or a list of functions to be called to run the hook.
2363 If the value is a function, it is called with no arguments.
2364 If it is a list, the elements are called, in order, with no arguments.
2366 Major modes should not use this function directly to run their mode
2367 hook; they should use `run-mode-hooks' instead.
2369 Do not use `make-local-variable' to make a hook variable buffer-local.
2370 Instead, use `add-hook' and specify t for the LOCAL argument.
2371 usage: (run-hooks &rest HOOKS) */)
2372 (ptrdiff_t nargs, Lisp_Object *args)
2374 ptrdiff_t i;
2376 for (i = 0; i < nargs; i++)
2377 run_hook (args[i]);
2379 return Qnil;
2382 DEFUN ("run-hook-with-args", Frun_hook_with_args,
2383 Srun_hook_with_args, 1, MANY, 0,
2384 doc: /* Run HOOK with the specified arguments ARGS.
2385 HOOK should be a symbol, a hook variable. The value of HOOK
2386 may be nil, a function, or a list of functions. Call each
2387 function in order with arguments ARGS. The final return value
2388 is unspecified.
2390 Do not use `make-local-variable' to make a hook variable buffer-local.
2391 Instead, use `add-hook' and specify t for the LOCAL argument.
2392 usage: (run-hook-with-args HOOK &rest ARGS) */)
2393 (ptrdiff_t nargs, Lisp_Object *args)
2395 return run_hook_with_args (nargs, args, funcall_nil);
2398 /* NB this one still documents a specific non-nil return value.
2399 (As did run-hook-with-args and run-hook-with-args-until-failure
2400 until they were changed in 24.1.) */
2401 DEFUN ("run-hook-with-args-until-success", Frun_hook_with_args_until_success,
2402 Srun_hook_with_args_until_success, 1, MANY, 0,
2403 doc: /* Run HOOK with the specified arguments ARGS.
2404 HOOK should be a symbol, a hook variable. The value of HOOK
2405 may be nil, a function, or a list of functions. Call each
2406 function in order with arguments ARGS, stopping at the first
2407 one that returns non-nil, and return that value. Otherwise (if
2408 all functions return nil, or if there are no functions to call),
2409 return nil.
2411 Do not use `make-local-variable' to make a hook variable buffer-local.
2412 Instead, use `add-hook' and specify t for the LOCAL argument.
2413 usage: (run-hook-with-args-until-success HOOK &rest ARGS) */)
2414 (ptrdiff_t nargs, Lisp_Object *args)
2416 return run_hook_with_args (nargs, args, Ffuncall);
2419 static Lisp_Object
2420 funcall_not (ptrdiff_t nargs, Lisp_Object *args)
2422 return NILP (Ffuncall (nargs, args)) ? Qt : Qnil;
2425 DEFUN ("run-hook-with-args-until-failure", Frun_hook_with_args_until_failure,
2426 Srun_hook_with_args_until_failure, 1, MANY, 0,
2427 doc: /* Run HOOK with the specified arguments ARGS.
2428 HOOK should be a symbol, a hook variable. The value of HOOK
2429 may be nil, a function, or a list of functions. Call each
2430 function in order with arguments ARGS, stopping at the first
2431 one that returns nil, and return nil. Otherwise (if all functions
2432 return non-nil, or if there are no functions to call), return non-nil
2433 \(do not rely on the precise return value in this case).
2435 Do not use `make-local-variable' to make a hook variable buffer-local.
2436 Instead, use `add-hook' and specify t for the LOCAL argument.
2437 usage: (run-hook-with-args-until-failure HOOK &rest ARGS) */)
2438 (ptrdiff_t nargs, Lisp_Object *args)
2440 return NILP (run_hook_with_args (nargs, args, funcall_not)) ? Qt : Qnil;
2443 static Lisp_Object
2444 run_hook_wrapped_funcall (ptrdiff_t nargs, Lisp_Object *args)
2446 Lisp_Object tmp = args[0], ret;
2447 args[0] = args[1];
2448 args[1] = tmp;
2449 ret = Ffuncall (nargs, args);
2450 args[1] = args[0];
2451 args[0] = tmp;
2452 return ret;
2455 DEFUN ("run-hook-wrapped", Frun_hook_wrapped, Srun_hook_wrapped, 2, MANY, 0,
2456 doc: /* Run HOOK, passing each function through WRAP-FUNCTION.
2457 I.e. instead of calling each function FUN directly with arguments ARGS,
2458 it calls WRAP-FUNCTION with arguments FUN and ARGS.
2459 As soon as a call to WRAP-FUNCTION returns non-nil, `run-hook-wrapped'
2460 aborts and returns that value.
2461 usage: (run-hook-wrapped HOOK WRAP-FUNCTION &rest ARGS) */)
2462 (ptrdiff_t nargs, Lisp_Object *args)
2464 return run_hook_with_args (nargs, args, run_hook_wrapped_funcall);
2467 /* ARGS[0] should be a hook symbol.
2468 Call each of the functions in the hook value, passing each of them
2469 as arguments all the rest of ARGS (all NARGS - 1 elements).
2470 FUNCALL specifies how to call each function on the hook. */
2472 Lisp_Object
2473 run_hook_with_args (ptrdiff_t nargs, Lisp_Object *args,
2474 Lisp_Object (*funcall) (ptrdiff_t nargs, Lisp_Object *args))
2476 Lisp_Object sym, val, ret = Qnil;
2478 /* If we are dying or still initializing,
2479 don't do anything--it would probably crash if we tried. */
2480 if (NILP (Vrun_hooks))
2481 return Qnil;
2483 sym = args[0];
2484 val = find_symbol_value (sym);
2486 if (EQ (val, Qunbound) || NILP (val))
2487 return ret;
2488 else if (!CONSP (val) || FUNCTIONP (val))
2490 args[0] = val;
2491 return funcall (nargs, args);
2493 else
2495 Lisp_Object global_vals = Qnil;
2497 for (;
2498 CONSP (val) && NILP (ret);
2499 val = XCDR (val))
2501 if (EQ (XCAR (val), Qt))
2503 /* t indicates this hook has a local binding;
2504 it means to run the global binding too. */
2505 global_vals = Fdefault_value (sym);
2506 if (NILP (global_vals)) continue;
2508 if (!CONSP (global_vals) || EQ (XCAR (global_vals), Qlambda))
2510 args[0] = global_vals;
2511 ret = funcall (nargs, args);
2513 else
2515 for (;
2516 CONSP (global_vals) && NILP (ret);
2517 global_vals = XCDR (global_vals))
2519 args[0] = XCAR (global_vals);
2520 /* In a global value, t should not occur. If it does, we
2521 must ignore it to avoid an endless loop. */
2522 if (!EQ (args[0], Qt))
2523 ret = funcall (nargs, args);
2527 else
2529 args[0] = XCAR (val);
2530 ret = funcall (nargs, args);
2534 return ret;
2538 /* Run the hook HOOK, giving each function no args. */
2540 void
2541 run_hook (Lisp_Object hook)
2543 Frun_hook_with_args (1, &hook);
2546 /* Run the hook HOOK, giving each function the two args ARG1 and ARG2. */
2548 void
2549 run_hook_with_args_2 (Lisp_Object hook, Lisp_Object arg1, Lisp_Object arg2)
2551 CALLN (Frun_hook_with_args, hook, arg1, arg2);
2554 /* Apply fn to arg. */
2555 Lisp_Object
2556 apply1 (Lisp_Object fn, Lisp_Object arg)
2558 return NILP (arg) ? Ffuncall (1, &fn) : CALLN (Fapply, fn, arg);
2561 /* Call function fn on no arguments. */
2562 Lisp_Object
2563 call0 (Lisp_Object fn)
2565 return Ffuncall (1, &fn);
2568 /* Call function fn with 1 argument arg1. */
2569 /* ARGSUSED */
2570 Lisp_Object
2571 call1 (Lisp_Object fn, Lisp_Object arg1)
2573 return CALLN (Ffuncall, fn, arg1);
2576 /* Call function fn with 2 arguments arg1, arg2. */
2577 /* ARGSUSED */
2578 Lisp_Object
2579 call2 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2)
2581 return CALLN (Ffuncall, fn, arg1, arg2);
2584 /* Call function fn with 3 arguments arg1, arg2, arg3. */
2585 /* ARGSUSED */
2586 Lisp_Object
2587 call3 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2589 return CALLN (Ffuncall, fn, arg1, arg2, arg3);
2592 /* Call function fn with 4 arguments arg1, arg2, arg3, arg4. */
2593 /* ARGSUSED */
2594 Lisp_Object
2595 call4 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2596 Lisp_Object arg4)
2598 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4);
2601 /* Call function fn with 5 arguments arg1, arg2, arg3, arg4, arg5. */
2602 /* ARGSUSED */
2603 Lisp_Object
2604 call5 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2605 Lisp_Object arg4, Lisp_Object arg5)
2607 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5);
2610 /* Call function fn with 6 arguments arg1, arg2, arg3, arg4, arg5, arg6. */
2611 /* ARGSUSED */
2612 Lisp_Object
2613 call6 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2614 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6)
2616 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6);
2619 /* Call function fn with 7 arguments arg1, arg2, arg3, arg4, arg5, arg6, arg7. */
2620 /* ARGSUSED */
2621 Lisp_Object
2622 call7 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2623 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6, Lisp_Object arg7)
2625 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
2628 DEFUN ("functionp", Ffunctionp, Sfunctionp, 1, 1, 0,
2629 doc: /* Non-nil if OBJECT is a function. */)
2630 (Lisp_Object object)
2632 if (FUNCTIONP (object))
2633 return Qt;
2634 return Qnil;
2637 DEFUN ("funcall", Ffuncall, Sfuncall, 1, MANY, 0,
2638 doc: /* Call first argument as a function, passing remaining arguments to it.
2639 Return the value that function returns.
2640 Thus, (funcall \\='cons \\='x \\='y) returns (x . y).
2641 usage: (funcall FUNCTION &rest ARGUMENTS) */)
2642 (ptrdiff_t nargs, Lisp_Object *args)
2644 Lisp_Object fun, original_fun;
2645 Lisp_Object funcar;
2646 ptrdiff_t numargs = nargs - 1;
2647 Lisp_Object lisp_numargs;
2648 Lisp_Object val;
2649 Lisp_Object *internal_args;
2650 ptrdiff_t count;
2652 QUIT;
2654 if (++lisp_eval_depth > max_lisp_eval_depth)
2656 if (max_lisp_eval_depth < 100)
2657 max_lisp_eval_depth = 100;
2658 if (lisp_eval_depth > max_lisp_eval_depth)
2659 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2662 count = record_in_backtrace (args[0], &args[1], nargs - 1);
2664 maybe_gc ();
2666 if (debug_on_next_call)
2667 do_debug_on_call (Qlambda, count);
2669 check_cons_list ();
2671 original_fun = args[0];
2673 retry:
2675 /* Optimize for no indirection. */
2676 fun = original_fun;
2677 if (SYMBOLP (fun) && !NILP (fun)
2678 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2679 fun = indirect_function (fun);
2681 if (SUBRP (fun))
2683 if (numargs < XSUBR (fun)->min_args
2684 || (XSUBR (fun)->max_args >= 0 && XSUBR (fun)->max_args < numargs))
2686 XSETFASTINT (lisp_numargs, numargs);
2687 xsignal2 (Qwrong_number_of_arguments, original_fun, lisp_numargs);
2690 else if (XSUBR (fun)->max_args == UNEVALLED)
2691 xsignal1 (Qinvalid_function, original_fun);
2693 else if (XSUBR (fun)->max_args == MANY)
2694 val = (XSUBR (fun)->function.aMANY) (numargs, args + 1);
2695 else
2697 Lisp_Object internal_argbuf[8];
2698 if (XSUBR (fun)->max_args > numargs)
2700 eassert (XSUBR (fun)->max_args <= ARRAYELTS (internal_argbuf));
2701 internal_args = internal_argbuf;
2702 memcpy (internal_args, args + 1, numargs * word_size);
2703 memclear (internal_args + numargs,
2704 (XSUBR (fun)->max_args - numargs) * word_size);
2706 else
2707 internal_args = args + 1;
2708 switch (XSUBR (fun)->max_args)
2710 case 0:
2711 val = (XSUBR (fun)->function.a0 ());
2712 break;
2713 case 1:
2714 val = (XSUBR (fun)->function.a1 (internal_args[0]));
2715 break;
2716 case 2:
2717 val = (XSUBR (fun)->function.a2
2718 (internal_args[0], internal_args[1]));
2719 break;
2720 case 3:
2721 val = (XSUBR (fun)->function.a3
2722 (internal_args[0], internal_args[1], internal_args[2]));
2723 break;
2724 case 4:
2725 val = (XSUBR (fun)->function.a4
2726 (internal_args[0], internal_args[1], internal_args[2],
2727 internal_args[3]));
2728 break;
2729 case 5:
2730 val = (XSUBR (fun)->function.a5
2731 (internal_args[0], internal_args[1], internal_args[2],
2732 internal_args[3], internal_args[4]));
2733 break;
2734 case 6:
2735 val = (XSUBR (fun)->function.a6
2736 (internal_args[0], internal_args[1], internal_args[2],
2737 internal_args[3], internal_args[4], internal_args[5]));
2738 break;
2739 case 7:
2740 val = (XSUBR (fun)->function.a7
2741 (internal_args[0], internal_args[1], internal_args[2],
2742 internal_args[3], internal_args[4], internal_args[5],
2743 internal_args[6]));
2744 break;
2746 case 8:
2747 val = (XSUBR (fun)->function.a8
2748 (internal_args[0], internal_args[1], internal_args[2],
2749 internal_args[3], internal_args[4], internal_args[5],
2750 internal_args[6], internal_args[7]));
2751 break;
2753 default:
2755 /* If a subr takes more than 8 arguments without using MANY
2756 or UNEVALLED, we need to extend this function to support it.
2757 Until this is done, there is no way to call the function. */
2758 emacs_abort ();
2762 else if (COMPILEDP (fun))
2763 val = funcall_lambda (fun, numargs, args + 1);
2764 else
2766 if (NILP (fun))
2767 xsignal1 (Qvoid_function, original_fun);
2768 if (!CONSP (fun))
2769 xsignal1 (Qinvalid_function, original_fun);
2770 funcar = XCAR (fun);
2771 if (!SYMBOLP (funcar))
2772 xsignal1 (Qinvalid_function, original_fun);
2773 if (EQ (funcar, Qlambda)
2774 || EQ (funcar, Qclosure))
2775 val = funcall_lambda (fun, numargs, args + 1);
2776 else if (EQ (funcar, Qautoload))
2778 Fautoload_do_load (fun, original_fun, Qnil);
2779 check_cons_list ();
2780 goto retry;
2782 else
2783 xsignal1 (Qinvalid_function, original_fun);
2785 check_cons_list ();
2786 lisp_eval_depth--;
2787 if (backtrace_debug_on_exit (specpdl + count))
2788 val = call_debugger (list2 (Qexit, val));
2789 specpdl_ptr--;
2790 return val;
2793 static Lisp_Object
2794 apply_lambda (Lisp_Object fun, Lisp_Object args, ptrdiff_t count)
2796 Lisp_Object args_left;
2797 ptrdiff_t i;
2798 EMACS_INT numargs;
2799 Lisp_Object *arg_vector;
2800 Lisp_Object tem;
2801 USE_SAFE_ALLOCA;
2803 numargs = XFASTINT (Flength (args));
2804 SAFE_ALLOCA_LISP (arg_vector, numargs);
2805 args_left = args;
2807 for (i = 0; i < numargs; )
2809 tem = Fcar (args_left), args_left = Fcdr (args_left);
2810 tem = eval_sub (tem);
2811 arg_vector[i++] = tem;
2814 set_backtrace_args (specpdl + count, arg_vector, i);
2815 tem = funcall_lambda (fun, numargs, arg_vector);
2817 check_cons_list ();
2818 lisp_eval_depth--;
2819 /* Do the debug-on-exit now, while arg_vector still exists. */
2820 if (backtrace_debug_on_exit (specpdl + count))
2821 tem = call_debugger (list2 (Qexit, tem));
2822 SAFE_FREE ();
2823 specpdl_ptr--;
2824 return tem;
2827 /* Apply a Lisp function FUN to the NARGS evaluated arguments in ARG_VECTOR
2828 and return the result of evaluation.
2829 FUN must be either a lambda-expression or a compiled-code object. */
2831 static Lisp_Object
2832 funcall_lambda (Lisp_Object fun, ptrdiff_t nargs,
2833 register Lisp_Object *arg_vector)
2835 Lisp_Object val, syms_left, next, lexenv;
2836 ptrdiff_t count = SPECPDL_INDEX ();
2837 ptrdiff_t i;
2838 bool optional, rest;
2840 if (CONSP (fun))
2842 if (EQ (XCAR (fun), Qclosure))
2844 Lisp_Object cdr = XCDR (fun); /* Drop `closure'. */
2845 if (! CONSP (cdr))
2846 xsignal1 (Qinvalid_function, fun);
2847 fun = cdr;
2848 lexenv = XCAR (fun);
2850 else
2851 lexenv = Qnil;
2852 syms_left = XCDR (fun);
2853 if (CONSP (syms_left))
2854 syms_left = XCAR (syms_left);
2855 else
2856 xsignal1 (Qinvalid_function, fun);
2858 else if (COMPILEDP (fun))
2860 ptrdiff_t size = ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK;
2861 if (size <= COMPILED_STACK_DEPTH)
2862 xsignal1 (Qinvalid_function, fun);
2863 syms_left = AREF (fun, COMPILED_ARGLIST);
2864 if (INTEGERP (syms_left))
2865 /* A byte-code object with an integer args template means we
2866 shouldn't bind any arguments, instead just call the byte-code
2867 interpreter directly; it will push arguments as necessary.
2869 Byte-code objects with a nil args template (the default)
2870 have dynamically-bound arguments, and use the
2871 argument-binding code below instead (as do all interpreted
2872 functions, even lexically bound ones). */
2874 /* If we have not actually read the bytecode string
2875 and constants vector yet, fetch them from the file. */
2876 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2877 Ffetch_bytecode (fun);
2878 return exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2879 AREF (fun, COMPILED_CONSTANTS),
2880 AREF (fun, COMPILED_STACK_DEPTH),
2881 syms_left,
2882 nargs, arg_vector);
2884 lexenv = Qnil;
2886 else
2887 emacs_abort ();
2889 i = optional = rest = 0;
2890 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
2892 QUIT;
2894 next = XCAR (syms_left);
2895 if (!SYMBOLP (next))
2896 xsignal1 (Qinvalid_function, fun);
2898 if (EQ (next, Qand_rest))
2899 rest = 1;
2900 else if (EQ (next, Qand_optional))
2901 optional = 1;
2902 else
2904 Lisp_Object arg;
2905 if (rest)
2907 arg = Flist (nargs - i, &arg_vector[i]);
2908 i = nargs;
2910 else if (i < nargs)
2911 arg = arg_vector[i++];
2912 else if (!optional)
2913 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2914 else
2915 arg = Qnil;
2917 /* Bind the argument. */
2918 if (!NILP (lexenv) && SYMBOLP (next))
2919 /* Lexically bind NEXT by adding it to the lexenv alist. */
2920 lexenv = Fcons (Fcons (next, arg), lexenv);
2921 else
2922 /* Dynamically bind NEXT. */
2923 specbind (next, arg);
2927 if (!NILP (syms_left))
2928 xsignal1 (Qinvalid_function, fun);
2929 else if (i < nargs)
2930 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2932 if (!EQ (lexenv, Vinternal_interpreter_environment))
2933 /* Instantiate a new lexical environment. */
2934 specbind (Qinternal_interpreter_environment, lexenv);
2936 if (CONSP (fun))
2937 val = Fprogn (XCDR (XCDR (fun)));
2938 else
2940 /* If we have not actually read the bytecode string
2941 and constants vector yet, fetch them from the file. */
2942 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2943 Ffetch_bytecode (fun);
2944 val = exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2945 AREF (fun, COMPILED_CONSTANTS),
2946 AREF (fun, COMPILED_STACK_DEPTH),
2947 Qnil, 0, 0);
2950 return unbind_to (count, val);
2953 DEFUN ("func-arity", Ffunc_arity, Sfunc_arity, 1, 1, 0,
2954 doc: /* Return minimum and maximum number of args allowed for FUNCTION.
2955 FUNCTION must be a function of some kind.
2956 The returned value is a cons cell (MIN . MAX). MIN is the minimum number
2957 of args. MAX is the maximum number, or the symbol `many', for a
2958 function with `&rest' args, or `unevalled' for a special form. */)
2959 (Lisp_Object function)
2961 Lisp_Object original;
2962 Lisp_Object funcar;
2963 Lisp_Object result;
2965 original = function;
2967 retry:
2969 /* Optimize for no indirection. */
2970 function = original;
2971 if (SYMBOLP (function) && !NILP (function))
2973 function = XSYMBOL (function)->function;
2974 if (SYMBOLP (function))
2975 function = indirect_function (function);
2978 if (CONSP (function) && EQ (XCAR (function), Qmacro))
2979 function = XCDR (function);
2981 if (SUBRP (function))
2982 result = Fsubr_arity (function);
2983 else if (COMPILEDP (function))
2984 result = lambda_arity (function);
2985 else
2987 if (NILP (function))
2988 xsignal1 (Qvoid_function, original);
2989 if (!CONSP (function))
2990 xsignal1 (Qinvalid_function, original);
2991 funcar = XCAR (function);
2992 if (!SYMBOLP (funcar))
2993 xsignal1 (Qinvalid_function, original);
2994 if (EQ (funcar, Qlambda)
2995 || EQ (funcar, Qclosure))
2996 result = lambda_arity (function);
2997 else if (EQ (funcar, Qautoload))
2999 Fautoload_do_load (function, original, Qnil);
3000 goto retry;
3002 else
3003 xsignal1 (Qinvalid_function, original);
3005 return result;
3008 /* FUN must be either a lambda-expression or a compiled-code object. */
3009 static Lisp_Object
3010 lambda_arity (Lisp_Object fun)
3012 Lisp_Object syms_left;
3014 if (CONSP (fun))
3016 if (EQ (XCAR (fun), Qclosure))
3018 fun = XCDR (fun); /* Drop `closure'. */
3019 CHECK_LIST_CONS (fun, fun);
3021 syms_left = XCDR (fun);
3022 if (CONSP (syms_left))
3023 syms_left = XCAR (syms_left);
3024 else
3025 xsignal1 (Qinvalid_function, fun);
3027 else if (COMPILEDP (fun))
3029 ptrdiff_t size = ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK;
3030 if (size <= COMPILED_STACK_DEPTH)
3031 xsignal1 (Qinvalid_function, fun);
3032 syms_left = AREF (fun, COMPILED_ARGLIST);
3033 if (INTEGERP (syms_left))
3034 return get_byte_code_arity (syms_left);
3036 else
3037 emacs_abort ();
3039 EMACS_INT minargs = 0, maxargs = 0;
3040 bool optional = false;
3041 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
3043 Lisp_Object next = XCAR (syms_left);
3044 if (!SYMBOLP (next))
3045 xsignal1 (Qinvalid_function, fun);
3047 if (EQ (next, Qand_rest))
3048 return Fcons (make_number (minargs), Qmany);
3049 else if (EQ (next, Qand_optional))
3050 optional = true;
3051 else
3053 if (!optional)
3054 minargs++;
3055 maxargs++;
3059 if (!NILP (syms_left))
3060 xsignal1 (Qinvalid_function, fun);
3062 return Fcons (make_number (minargs), make_number (maxargs));
3065 DEFUN ("fetch-bytecode", Ffetch_bytecode, Sfetch_bytecode,
3066 1, 1, 0,
3067 doc: /* If byte-compiled OBJECT is lazy-loaded, fetch it now. */)
3068 (Lisp_Object object)
3070 Lisp_Object tem;
3072 if (COMPILEDP (object))
3074 ptrdiff_t size = ASIZE (object) & PSEUDOVECTOR_SIZE_MASK;
3075 if (size <= COMPILED_STACK_DEPTH)
3076 xsignal1 (Qinvalid_function, object);
3077 if (CONSP (AREF (object, COMPILED_BYTECODE)))
3079 tem = read_doc_string (AREF (object, COMPILED_BYTECODE));
3080 if (!CONSP (tem))
3082 tem = AREF (object, COMPILED_BYTECODE);
3083 if (CONSP (tem) && STRINGP (XCAR (tem)))
3084 error ("Invalid byte code in %s", SDATA (XCAR (tem)));
3085 else
3086 error ("Invalid byte code");
3088 ASET (object, COMPILED_BYTECODE, XCAR (tem));
3089 ASET (object, COMPILED_CONSTANTS, XCDR (tem));
3092 return object;
3095 /* Return true if SYMBOL currently has a let-binding
3096 which was made in the buffer that is now current. */
3098 bool
3099 let_shadows_buffer_binding_p (struct Lisp_Symbol *symbol)
3101 union specbinding *p;
3102 Lisp_Object buf = Fcurrent_buffer ();
3104 for (p = specpdl_ptr; p > specpdl; )
3105 if ((--p)->kind > SPECPDL_LET)
3107 struct Lisp_Symbol *let_bound_symbol = XSYMBOL (specpdl_symbol (p));
3108 eassert (let_bound_symbol->redirect != SYMBOL_VARALIAS);
3109 if (symbol == let_bound_symbol
3110 && EQ (specpdl_where (p), buf))
3111 return 1;
3114 return 0;
3117 bool
3118 let_shadows_global_binding_p (Lisp_Object symbol)
3120 union specbinding *p;
3122 for (p = specpdl_ptr; p > specpdl; )
3123 if ((--p)->kind >= SPECPDL_LET && EQ (specpdl_symbol (p), symbol))
3124 return 1;
3126 return 0;
3129 /* `specpdl_ptr' describes which variable is
3130 let-bound, so it can be properly undone when we unbind_to.
3131 It can be either a plain SPECPDL_LET or a SPECPDL_LET_LOCAL/DEFAULT.
3132 - SYMBOL is the variable being bound. Note that it should not be
3133 aliased (i.e. when let-binding V1 that's aliased to V2, we want
3134 to record V2 here).
3135 - WHERE tells us in which buffer the binding took place.
3136 This is used for SPECPDL_LET_LOCAL bindings (i.e. bindings to a
3137 buffer-local variable) as well as for SPECPDL_LET_DEFAULT bindings,
3138 i.e. bindings to the default value of a variable which can be
3139 buffer-local. */
3141 void
3142 specbind (Lisp_Object symbol, Lisp_Object value)
3144 struct Lisp_Symbol *sym;
3146 CHECK_SYMBOL (symbol);
3147 sym = XSYMBOL (symbol);
3149 start:
3150 switch (sym->redirect)
3152 case SYMBOL_VARALIAS:
3153 sym = indirect_variable (sym); XSETSYMBOL (symbol, sym); goto start;
3154 case SYMBOL_PLAINVAL:
3155 /* The most common case is that of a non-constant symbol with a
3156 trivial value. Make that as fast as we can. */
3157 specpdl_ptr->let.kind = SPECPDL_LET;
3158 specpdl_ptr->let.symbol = symbol;
3159 specpdl_ptr->let.old_value = SYMBOL_VAL (sym);
3160 grow_specpdl ();
3161 if (!sym->constant)
3162 SET_SYMBOL_VAL (sym, value);
3163 else
3164 set_internal (symbol, value, Qnil, 1);
3165 break;
3166 case SYMBOL_LOCALIZED:
3167 if (SYMBOL_BLV (sym)->frame_local)
3168 error ("Frame-local vars cannot be let-bound");
3169 case SYMBOL_FORWARDED:
3171 Lisp_Object ovalue = find_symbol_value (symbol);
3172 specpdl_ptr->let.kind = SPECPDL_LET_LOCAL;
3173 specpdl_ptr->let.symbol = symbol;
3174 specpdl_ptr->let.old_value = ovalue;
3175 specpdl_ptr->let.where = Fcurrent_buffer ();
3177 eassert (sym->redirect != SYMBOL_LOCALIZED
3178 || (EQ (SYMBOL_BLV (sym)->where, Fcurrent_buffer ())));
3180 if (sym->redirect == SYMBOL_LOCALIZED)
3182 if (!blv_found (SYMBOL_BLV (sym)))
3183 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3185 else if (BUFFER_OBJFWDP (SYMBOL_FWD (sym)))
3187 /* If SYMBOL is a per-buffer variable which doesn't have a
3188 buffer-local value here, make the `let' change the global
3189 value by changing the value of SYMBOL in all buffers not
3190 having their own value. This is consistent with what
3191 happens with other buffer-local variables. */
3192 if (NILP (Flocal_variable_p (symbol, Qnil)))
3194 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3195 grow_specpdl ();
3196 Fset_default (symbol, value);
3197 return;
3200 else
3201 specpdl_ptr->let.kind = SPECPDL_LET;
3203 grow_specpdl ();
3204 set_internal (symbol, value, Qnil, 1);
3205 break;
3207 default: emacs_abort ();
3211 /* Push unwind-protect entries of various types. */
3213 void
3214 record_unwind_protect (void (*function) (Lisp_Object), Lisp_Object arg)
3216 specpdl_ptr->unwind.kind = SPECPDL_UNWIND;
3217 specpdl_ptr->unwind.func = function;
3218 specpdl_ptr->unwind.arg = arg;
3219 grow_specpdl ();
3222 void
3223 record_unwind_protect_ptr (void (*function) (void *), void *arg)
3225 specpdl_ptr->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3226 specpdl_ptr->unwind_ptr.func = function;
3227 specpdl_ptr->unwind_ptr.arg = arg;
3228 grow_specpdl ();
3231 void
3232 record_unwind_protect_int (void (*function) (int), int arg)
3234 specpdl_ptr->unwind_int.kind = SPECPDL_UNWIND_INT;
3235 specpdl_ptr->unwind_int.func = function;
3236 specpdl_ptr->unwind_int.arg = arg;
3237 grow_specpdl ();
3240 void
3241 record_unwind_protect_void (void (*function) (void))
3243 specpdl_ptr->unwind_void.kind = SPECPDL_UNWIND_VOID;
3244 specpdl_ptr->unwind_void.func = function;
3245 grow_specpdl ();
3248 static void
3249 do_nothing (void)
3252 /* Push an unwind-protect entry that does nothing, so that
3253 set_unwind_protect_ptr can overwrite it later. */
3255 void
3256 record_unwind_protect_nothing (void)
3258 record_unwind_protect_void (do_nothing);
3261 /* Clear the unwind-protect entry COUNT, so that it does nothing.
3262 It need not be at the top of the stack. */
3264 void
3265 clear_unwind_protect (ptrdiff_t count)
3267 union specbinding *p = specpdl + count;
3268 p->unwind_void.kind = SPECPDL_UNWIND_VOID;
3269 p->unwind_void.func = do_nothing;
3272 /* Set the unwind-protect entry COUNT so that it invokes FUNC (ARG).
3273 It need not be at the top of the stack. Discard the entry's
3274 previous value without invoking it. */
3276 void
3277 set_unwind_protect (ptrdiff_t count, void (*func) (Lisp_Object),
3278 Lisp_Object arg)
3280 union specbinding *p = specpdl + count;
3281 p->unwind.kind = SPECPDL_UNWIND;
3282 p->unwind.func = func;
3283 p->unwind.arg = arg;
3286 void
3287 set_unwind_protect_ptr (ptrdiff_t count, void (*func) (void *), void *arg)
3289 union specbinding *p = specpdl + count;
3290 p->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3291 p->unwind_ptr.func = func;
3292 p->unwind_ptr.arg = arg;
3295 /* Pop and execute entries from the unwind-protect stack until the
3296 depth COUNT is reached. Return VALUE. */
3298 Lisp_Object
3299 unbind_to (ptrdiff_t count, Lisp_Object value)
3301 Lisp_Object quitf = Vquit_flag;
3303 Vquit_flag = Qnil;
3305 while (specpdl_ptr != specpdl + count)
3307 /* Decrement specpdl_ptr before we do the work to unbind it, so
3308 that an error in unbinding won't try to unbind the same entry
3309 again. Take care to copy any parts of the binding needed
3310 before invoking any code that can make more bindings. */
3312 specpdl_ptr--;
3314 switch (specpdl_ptr->kind)
3316 case SPECPDL_UNWIND:
3317 specpdl_ptr->unwind.func (specpdl_ptr->unwind.arg);
3318 break;
3319 case SPECPDL_UNWIND_PTR:
3320 specpdl_ptr->unwind_ptr.func (specpdl_ptr->unwind_ptr.arg);
3321 break;
3322 case SPECPDL_UNWIND_INT:
3323 specpdl_ptr->unwind_int.func (specpdl_ptr->unwind_int.arg);
3324 break;
3325 case SPECPDL_UNWIND_VOID:
3326 specpdl_ptr->unwind_void.func ();
3327 break;
3328 case SPECPDL_BACKTRACE:
3329 break;
3330 case SPECPDL_LET:
3331 { /* If variable has a trivial value (no forwarding), we can
3332 just set it. No need to check for constant symbols here,
3333 since that was already done by specbind. */
3334 Lisp_Object sym = specpdl_symbol (specpdl_ptr);
3335 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3337 SET_SYMBOL_VAL (XSYMBOL (sym),
3338 specpdl_old_value (specpdl_ptr));
3339 break;
3341 else
3342 { /* FALLTHROUGH!!
3343 NOTE: we only ever come here if make_local_foo was used for
3344 the first time on this var within this let. */
3347 case SPECPDL_LET_DEFAULT:
3348 Fset_default (specpdl_symbol (specpdl_ptr),
3349 specpdl_old_value (specpdl_ptr));
3350 break;
3351 case SPECPDL_LET_LOCAL:
3353 Lisp_Object symbol = specpdl_symbol (specpdl_ptr);
3354 Lisp_Object where = specpdl_where (specpdl_ptr);
3355 Lisp_Object old_value = specpdl_old_value (specpdl_ptr);
3356 eassert (BUFFERP (where));
3358 /* If this was a local binding, reset the value in the appropriate
3359 buffer, but only if that buffer's binding still exists. */
3360 if (!NILP (Flocal_variable_p (symbol, where)))
3361 set_internal (symbol, old_value, where, 1);
3363 break;
3367 if (NILP (Vquit_flag) && !NILP (quitf))
3368 Vquit_flag = quitf;
3370 return value;
3373 DEFUN ("special-variable-p", Fspecial_variable_p, Sspecial_variable_p, 1, 1, 0,
3374 doc: /* Return non-nil if SYMBOL's global binding has been declared special.
3375 A special variable is one that will be bound dynamically, even in a
3376 context where binding is lexical by default. */)
3377 (Lisp_Object symbol)
3379 CHECK_SYMBOL (symbol);
3380 return XSYMBOL (symbol)->declared_special ? Qt : Qnil;
3384 DEFUN ("backtrace-debug", Fbacktrace_debug, Sbacktrace_debug, 2, 2, 0,
3385 doc: /* Set the debug-on-exit flag of eval frame LEVEL levels down to FLAG.
3386 The debugger is entered when that frame exits, if the flag is non-nil. */)
3387 (Lisp_Object level, Lisp_Object flag)
3389 union specbinding *pdl = backtrace_top ();
3390 register EMACS_INT i;
3392 CHECK_NUMBER (level);
3394 for (i = 0; backtrace_p (pdl) && i < XINT (level); i++)
3395 pdl = backtrace_next (pdl);
3397 if (backtrace_p (pdl))
3398 set_backtrace_debug_on_exit (pdl, !NILP (flag));
3400 return flag;
3403 DEFUN ("backtrace", Fbacktrace, Sbacktrace, 0, 0, "",
3404 doc: /* Print a trace of Lisp function calls currently active.
3405 Output stream used is value of `standard-output'. */)
3406 (void)
3408 union specbinding *pdl = backtrace_top ();
3409 Lisp_Object tem;
3410 Lisp_Object old_print_level = Vprint_level;
3412 if (NILP (Vprint_level))
3413 XSETFASTINT (Vprint_level, 8);
3415 while (backtrace_p (pdl))
3417 write_string (backtrace_debug_on_exit (pdl) ? "* " : " ");
3418 if (backtrace_nargs (pdl) == UNEVALLED)
3420 Fprin1 (Fcons (backtrace_function (pdl), *backtrace_args (pdl)),
3421 Qnil);
3422 write_string ("\n");
3424 else
3426 tem = backtrace_function (pdl);
3427 if (debugger_stack_frame_as_list)
3428 write_string ("(");
3429 Fprin1 (tem, Qnil); /* This can QUIT. */
3430 if (!debugger_stack_frame_as_list)
3431 write_string ("(");
3433 ptrdiff_t i;
3434 for (i = 0; i < backtrace_nargs (pdl); i++)
3436 if (i || debugger_stack_frame_as_list)
3437 write_string(" ");
3438 Fprin1 (backtrace_args (pdl)[i], Qnil);
3441 write_string (")\n");
3443 pdl = backtrace_next (pdl);
3446 Vprint_level = old_print_level;
3447 return Qnil;
3450 static union specbinding *
3451 get_backtrace_frame (Lisp_Object nframes, Lisp_Object base)
3453 union specbinding *pdl = backtrace_top ();
3454 register EMACS_INT i;
3456 CHECK_NATNUM (nframes);
3458 if (!NILP (base))
3459 { /* Skip up to `base'. */
3460 base = Findirect_function (base, Qt);
3461 while (backtrace_p (pdl)
3462 && !EQ (base, Findirect_function (backtrace_function (pdl), Qt)))
3463 pdl = backtrace_next (pdl);
3466 /* Find the frame requested. */
3467 for (i = XFASTINT (nframes); i > 0 && backtrace_p (pdl); i--)
3468 pdl = backtrace_next (pdl);
3470 return pdl;
3473 DEFUN ("backtrace-frame", Fbacktrace_frame, Sbacktrace_frame, 1, 2, NULL,
3474 doc: /* Return the function and arguments NFRAMES up from current execution point.
3475 If that frame has not evaluated the arguments yet (or is a special form),
3476 the value is (nil FUNCTION ARG-FORMS...).
3477 If that frame has evaluated its arguments and called its function already,
3478 the value is (t FUNCTION ARG-VALUES...).
3479 A &rest arg is represented as the tail of the list ARG-VALUES.
3480 FUNCTION is whatever was supplied as car of evaluated list,
3481 or a lambda expression for macro calls.
3482 If NFRAMES is more than the number of frames, the value is nil.
3483 If BASE is non-nil, it should be a function and NFRAMES counts from its
3484 nearest activation frame. */)
3485 (Lisp_Object nframes, Lisp_Object base)
3487 union specbinding *pdl = get_backtrace_frame (nframes, base);
3489 if (!backtrace_p (pdl))
3490 return Qnil;
3491 if (backtrace_nargs (pdl) == UNEVALLED)
3492 return Fcons (Qnil,
3493 Fcons (backtrace_function (pdl), *backtrace_args (pdl)));
3494 else
3496 Lisp_Object tem = Flist (backtrace_nargs (pdl), backtrace_args (pdl));
3498 return Fcons (Qt, Fcons (backtrace_function (pdl), tem));
3502 /* For backtrace-eval, we want to temporarily unwind the last few elements of
3503 the specpdl stack, and then rewind them. We store the pre-unwind values
3504 directly in the pre-existing specpdl elements (i.e. we swap the current
3505 value and the old value stored in the specpdl), kind of like the inplace
3506 pointer-reversal trick. As it turns out, the rewind does the same as the
3507 unwind, except it starts from the other end of the specpdl stack, so we use
3508 the same function for both unwind and rewind. */
3509 static void
3510 backtrace_eval_unrewind (int distance)
3512 union specbinding *tmp = specpdl_ptr;
3513 int step = -1;
3514 if (distance < 0)
3515 { /* It's a rewind rather than unwind. */
3516 tmp += distance - 1;
3517 step = 1;
3518 distance = -distance;
3521 for (; distance > 0; distance--)
3523 tmp += step;
3524 switch (tmp->kind)
3526 /* FIXME: Ideally we'd like to "temporarily unwind" (some of) those
3527 unwind_protect, but the problem is that we don't know how to
3528 rewind them afterwards. */
3529 case SPECPDL_UNWIND:
3531 Lisp_Object oldarg = tmp->unwind.arg;
3532 if (tmp->unwind.func == set_buffer_if_live)
3533 tmp->unwind.arg = Fcurrent_buffer ();
3534 else if (tmp->unwind.func == save_excursion_restore)
3535 tmp->unwind.arg = save_excursion_save ();
3536 else
3537 break;
3538 tmp->unwind.func (oldarg);
3539 break;
3542 case SPECPDL_UNWIND_PTR:
3543 case SPECPDL_UNWIND_INT:
3544 case SPECPDL_UNWIND_VOID:
3545 case SPECPDL_BACKTRACE:
3546 break;
3547 case SPECPDL_LET:
3548 { /* If variable has a trivial value (no forwarding), we can
3549 just set it. No need to check for constant symbols here,
3550 since that was already done by specbind. */
3551 Lisp_Object sym = specpdl_symbol (tmp);
3552 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3554 Lisp_Object old_value = specpdl_old_value (tmp);
3555 set_specpdl_old_value (tmp, SYMBOL_VAL (XSYMBOL (sym)));
3556 SET_SYMBOL_VAL (XSYMBOL (sym), old_value);
3557 break;
3559 else
3560 { /* FALLTHROUGH!!
3561 NOTE: we only ever come here if make_local_foo was used for
3562 the first time on this var within this let. */
3565 case SPECPDL_LET_DEFAULT:
3567 Lisp_Object sym = specpdl_symbol (tmp);
3568 Lisp_Object old_value = specpdl_old_value (tmp);
3569 set_specpdl_old_value (tmp, Fdefault_value (sym));
3570 Fset_default (sym, old_value);
3572 break;
3573 case SPECPDL_LET_LOCAL:
3575 Lisp_Object symbol = specpdl_symbol (tmp);
3576 Lisp_Object where = specpdl_where (tmp);
3577 Lisp_Object old_value = specpdl_old_value (tmp);
3578 eassert (BUFFERP (where));
3580 /* If this was a local binding, reset the value in the appropriate
3581 buffer, but only if that buffer's binding still exists. */
3582 if (!NILP (Flocal_variable_p (symbol, where)))
3584 set_specpdl_old_value
3585 (tmp, Fbuffer_local_value (symbol, where));
3586 set_internal (symbol, old_value, where, 1);
3589 break;
3594 DEFUN ("backtrace-eval", Fbacktrace_eval, Sbacktrace_eval, 2, 3, NULL,
3595 doc: /* Evaluate EXP in the context of some activation frame.
3596 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3597 (Lisp_Object exp, Lisp_Object nframes, Lisp_Object base)
3599 union specbinding *pdl = get_backtrace_frame (nframes, base);
3600 ptrdiff_t count = SPECPDL_INDEX ();
3601 ptrdiff_t distance = specpdl_ptr - pdl;
3602 eassert (distance >= 0);
3604 if (!backtrace_p (pdl))
3605 error ("Activation frame not found!");
3607 backtrace_eval_unrewind (distance);
3608 record_unwind_protect_int (backtrace_eval_unrewind, -distance);
3610 /* Use eval_sub rather than Feval since the main motivation behind
3611 backtrace-eval is to be able to get/set the value of lexical variables
3612 from the debugger. */
3613 return unbind_to (count, eval_sub (exp));
3616 DEFUN ("backtrace--locals", Fbacktrace__locals, Sbacktrace__locals, 1, 2, NULL,
3617 doc: /* Return names and values of local variables of a stack frame.
3618 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3619 (Lisp_Object nframes, Lisp_Object base)
3621 union specbinding *frame = get_backtrace_frame (nframes, base);
3622 union specbinding *prevframe
3623 = get_backtrace_frame (make_number (XFASTINT (nframes) - 1), base);
3624 ptrdiff_t distance = specpdl_ptr - frame;
3625 Lisp_Object result = Qnil;
3626 eassert (distance >= 0);
3628 if (!backtrace_p (prevframe))
3629 error ("Activation frame not found!");
3630 if (!backtrace_p (frame))
3631 error ("Activation frame not found!");
3633 /* The specpdl entries normally contain the symbol being bound along with its
3634 `old_value', so it can be restored. The new value to which it is bound is
3635 available in one of two places: either in the current value of the
3636 variable (if it hasn't been rebound yet) or in the `old_value' slot of the
3637 next specpdl entry for it.
3638 `backtrace_eval_unrewind' happens to swap the role of `old_value'
3639 and "new value", so we abuse it here, to fetch the new value.
3640 It's ugly (we'd rather not modify global data) and a bit inefficient,
3641 but it does the job for now. */
3642 backtrace_eval_unrewind (distance);
3644 /* Grab values. */
3646 union specbinding *tmp = prevframe;
3647 for (; tmp > frame; tmp--)
3649 switch (tmp->kind)
3651 case SPECPDL_LET:
3652 case SPECPDL_LET_DEFAULT:
3653 case SPECPDL_LET_LOCAL:
3655 Lisp_Object sym = specpdl_symbol (tmp);
3656 Lisp_Object val = specpdl_old_value (tmp);
3657 if (EQ (sym, Qinternal_interpreter_environment))
3659 Lisp_Object env = val;
3660 for (; CONSP (env); env = XCDR (env))
3662 Lisp_Object binding = XCAR (env);
3663 if (CONSP (binding))
3664 result = Fcons (Fcons (XCAR (binding),
3665 XCDR (binding)),
3666 result);
3669 else
3670 result = Fcons (Fcons (sym, val), result);
3672 break;
3674 case SPECPDL_UNWIND:
3675 case SPECPDL_UNWIND_PTR:
3676 case SPECPDL_UNWIND_INT:
3677 case SPECPDL_UNWIND_VOID:
3678 case SPECPDL_BACKTRACE:
3679 break;
3681 default:
3682 emacs_abort ();
3687 /* Restore values from specpdl to original place. */
3688 backtrace_eval_unrewind (-distance);
3690 return result;
3694 void
3695 mark_specpdl (void)
3697 union specbinding *pdl;
3698 for (pdl = specpdl; pdl != specpdl_ptr; pdl++)
3700 switch (pdl->kind)
3702 case SPECPDL_UNWIND:
3703 mark_object (specpdl_arg (pdl));
3704 break;
3706 case SPECPDL_BACKTRACE:
3708 ptrdiff_t nargs = backtrace_nargs (pdl);
3709 mark_object (backtrace_function (pdl));
3710 if (nargs == UNEVALLED)
3711 nargs = 1;
3712 while (nargs--)
3713 mark_object (backtrace_args (pdl)[nargs]);
3715 break;
3717 case SPECPDL_LET_DEFAULT:
3718 case SPECPDL_LET_LOCAL:
3719 mark_object (specpdl_where (pdl));
3720 /* Fall through. */
3721 case SPECPDL_LET:
3722 mark_object (specpdl_symbol (pdl));
3723 mark_object (specpdl_old_value (pdl));
3724 break;
3726 case SPECPDL_UNWIND_PTR:
3727 case SPECPDL_UNWIND_INT:
3728 case SPECPDL_UNWIND_VOID:
3729 break;
3731 default:
3732 emacs_abort ();
3737 void
3738 get_backtrace (Lisp_Object array)
3740 union specbinding *pdl = backtrace_next (backtrace_top ());
3741 ptrdiff_t i = 0, asize = ASIZE (array);
3743 /* Copy the backtrace contents into working memory. */
3744 for (; i < asize; i++)
3746 if (backtrace_p (pdl))
3748 ASET (array, i, backtrace_function (pdl));
3749 pdl = backtrace_next (pdl);
3751 else
3752 ASET (array, i, Qnil);
3756 Lisp_Object backtrace_top_function (void)
3758 union specbinding *pdl = backtrace_top ();
3759 return (backtrace_p (pdl) ? backtrace_function (pdl) : Qnil);
3762 void
3763 syms_of_eval (void)
3765 DEFVAR_INT ("max-specpdl-size", max_specpdl_size,
3766 doc: /* Limit on number of Lisp variable bindings and `unwind-protect's.
3767 If Lisp code tries to increase the total number past this amount,
3768 an error is signaled.
3769 You can safely use a value considerably larger than the default value,
3770 if that proves inconveniently small. However, if you increase it too far,
3771 Emacs could run out of memory trying to make the stack bigger.
3772 Note that this limit may be silently increased by the debugger
3773 if `debug-on-error' or `debug-on-quit' is set. */);
3775 DEFVAR_INT ("max-lisp-eval-depth", max_lisp_eval_depth,
3776 doc: /* Limit on depth in `eval', `apply' and `funcall' before error.
3778 This limit serves to catch infinite recursions for you before they cause
3779 actual stack overflow in C, which would be fatal for Emacs.
3780 You can safely make it considerably larger than its default value,
3781 if that proves inconveniently small. However, if you increase it too far,
3782 Emacs could overflow the real C stack, and crash. */);
3784 DEFVAR_LISP ("quit-flag", Vquit_flag,
3785 doc: /* Non-nil causes `eval' to abort, unless `inhibit-quit' is non-nil.
3786 If the value is t, that means do an ordinary quit.
3787 If the value equals `throw-on-input', that means quit by throwing
3788 to the tag specified in `throw-on-input'; it's for handling `while-no-input'.
3789 Typing C-g sets `quit-flag' to t, regardless of `inhibit-quit',
3790 but `inhibit-quit' non-nil prevents anything from taking notice of that. */);
3791 Vquit_flag = Qnil;
3793 DEFVAR_LISP ("inhibit-quit", Vinhibit_quit,
3794 doc: /* Non-nil inhibits C-g quitting from happening immediately.
3795 Note that `quit-flag' will still be set by typing C-g,
3796 so a quit will be signaled as soon as `inhibit-quit' is nil.
3797 To prevent this happening, set `quit-flag' to nil
3798 before making `inhibit-quit' nil. */);
3799 Vinhibit_quit = Qnil;
3801 DEFSYM (Qsetq, "setq");
3802 DEFSYM (Qinhibit_quit, "inhibit-quit");
3803 DEFSYM (Qautoload, "autoload");
3804 DEFSYM (Qinhibit_debugger, "inhibit-debugger");
3805 DEFSYM (Qmacro, "macro");
3807 /* Note that the process handling also uses Qexit, but we don't want
3808 to staticpro it twice, so we just do it here. */
3809 DEFSYM (Qexit, "exit");
3811 DEFSYM (Qinteractive, "interactive");
3812 DEFSYM (Qcommandp, "commandp");
3813 DEFSYM (Qand_rest, "&rest");
3814 DEFSYM (Qand_optional, "&optional");
3815 DEFSYM (Qclosure, "closure");
3816 DEFSYM (QCdocumentation, ":documentation");
3817 DEFSYM (Qdebug, "debug");
3819 DEFVAR_LISP ("inhibit-debugger", Vinhibit_debugger,
3820 doc: /* Non-nil means never enter the debugger.
3821 Normally set while the debugger is already active, to avoid recursive
3822 invocations. */);
3823 Vinhibit_debugger = Qnil;
3825 DEFVAR_LISP ("debug-on-error", Vdebug_on_error,
3826 doc: /* Non-nil means enter debugger if an error is signaled.
3827 Does not apply to errors handled by `condition-case' or those
3828 matched by `debug-ignored-errors'.
3829 If the value is a list, an error only means to enter the debugger
3830 if one of its condition symbols appears in the list.
3831 When you evaluate an expression interactively, this variable
3832 is temporarily non-nil if `eval-expression-debug-on-error' is non-nil.
3833 The command `toggle-debug-on-error' toggles this.
3834 See also the variable `debug-on-quit' and `inhibit-debugger'. */);
3835 Vdebug_on_error = Qnil;
3837 DEFVAR_LISP ("debug-ignored-errors", Vdebug_ignored_errors,
3838 doc: /* List of errors for which the debugger should not be called.
3839 Each element may be a condition-name or a regexp that matches error messages.
3840 If any element applies to a given error, that error skips the debugger
3841 and just returns to top level.
3842 This overrides the variable `debug-on-error'.
3843 It does not apply to errors handled by `condition-case'. */);
3844 Vdebug_ignored_errors = Qnil;
3846 DEFVAR_BOOL ("debug-on-quit", debug_on_quit,
3847 doc: /* Non-nil means enter debugger if quit is signaled (C-g, for example).
3848 Does not apply if quit is handled by a `condition-case'. */);
3849 debug_on_quit = 0;
3851 DEFVAR_BOOL ("debug-on-next-call", debug_on_next_call,
3852 doc: /* Non-nil means enter debugger before next `eval', `apply' or `funcall'. */);
3854 DEFVAR_BOOL ("debugger-may-continue", debugger_may_continue,
3855 doc: /* Non-nil means debugger may continue execution.
3856 This is nil when the debugger is called under circumstances where it
3857 might not be safe to continue. */);
3858 debugger_may_continue = 1;
3860 DEFVAR_BOOL ("debugger-stack-frame-as-list", debugger_stack_frame_as_list,
3861 doc: /* Non-nil means display call stack frames as lists. */);
3862 debugger_stack_frame_as_list = 0;
3864 DEFVAR_LISP ("debugger", Vdebugger,
3865 doc: /* Function to call to invoke debugger.
3866 If due to frame exit, args are `exit' and the value being returned;
3867 this function's value will be returned instead of that.
3868 If due to error, args are `error' and a list of the args to `signal'.
3869 If due to `apply' or `funcall' entry, one arg, `lambda'.
3870 If due to `eval' entry, one arg, t. */);
3871 Vdebugger = Qnil;
3873 DEFVAR_LISP ("signal-hook-function", Vsignal_hook_function,
3874 doc: /* If non-nil, this is a function for `signal' to call.
3875 It receives the same arguments that `signal' was given.
3876 The Edebug package uses this to regain control. */);
3877 Vsignal_hook_function = Qnil;
3879 DEFVAR_LISP ("debug-on-signal", Vdebug_on_signal,
3880 doc: /* Non-nil means call the debugger regardless of condition handlers.
3881 Note that `debug-on-error', `debug-on-quit' and friends
3882 still determine whether to handle the particular condition. */);
3883 Vdebug_on_signal = Qnil;
3885 /* When lexical binding is being used,
3886 Vinternal_interpreter_environment is non-nil, and contains an alist
3887 of lexically-bound variable, or (t), indicating an empty
3888 environment. The lisp name of this variable would be
3889 `internal-interpreter-environment' if it weren't hidden.
3890 Every element of this list can be either a cons (VAR . VAL)
3891 specifying a lexical binding, or a single symbol VAR indicating
3892 that this variable should use dynamic scoping. */
3893 DEFSYM (Qinternal_interpreter_environment,
3894 "internal-interpreter-environment");
3895 DEFVAR_LISP ("internal-interpreter-environment",
3896 Vinternal_interpreter_environment,
3897 doc: /* If non-nil, the current lexical environment of the lisp interpreter.
3898 When lexical binding is not being used, this variable is nil.
3899 A value of `(t)' indicates an empty environment, otherwise it is an
3900 alist of active lexical bindings. */);
3901 Vinternal_interpreter_environment = Qnil;
3902 /* Don't export this variable to Elisp, so no one can mess with it
3903 (Just imagine if someone makes it buffer-local). */
3904 Funintern (Qinternal_interpreter_environment, Qnil);
3906 Vrun_hooks = intern_c_string ("run-hooks");
3907 staticpro (&Vrun_hooks);
3909 staticpro (&Vautoload_queue);
3910 Vautoload_queue = Qnil;
3911 staticpro (&Vsignaling_function);
3912 Vsignaling_function = Qnil;
3914 inhibit_lisp_code = Qnil;
3916 defsubr (&Sor);
3917 defsubr (&Sand);
3918 defsubr (&Sif);
3919 defsubr (&Scond);
3920 defsubr (&Sprogn);
3921 defsubr (&Sprog1);
3922 defsubr (&Sprog2);
3923 defsubr (&Ssetq);
3924 defsubr (&Squote);
3925 defsubr (&Sfunction);
3926 defsubr (&Sdefault_toplevel_value);
3927 defsubr (&Sset_default_toplevel_value);
3928 defsubr (&Sdefvar);
3929 defsubr (&Sdefvaralias);
3930 defsubr (&Sdefconst);
3931 defsubr (&Smake_var_non_special);
3932 defsubr (&Slet);
3933 defsubr (&SletX);
3934 defsubr (&Swhile);
3935 defsubr (&Smacroexpand);
3936 defsubr (&Scatch);
3937 defsubr (&Sthrow);
3938 defsubr (&Sunwind_protect);
3939 defsubr (&Scondition_case);
3940 defsubr (&Ssignal);
3941 defsubr (&Scommandp);
3942 defsubr (&Sautoload);
3943 defsubr (&Sautoload_do_load);
3944 defsubr (&Seval);
3945 defsubr (&Sapply);
3946 defsubr (&Sfuncall);
3947 defsubr (&Sfunc_arity);
3948 defsubr (&Srun_hooks);
3949 defsubr (&Srun_hook_with_args);
3950 defsubr (&Srun_hook_with_args_until_success);
3951 defsubr (&Srun_hook_with_args_until_failure);
3952 defsubr (&Srun_hook_wrapped);
3953 defsubr (&Sfetch_bytecode);
3954 defsubr (&Sbacktrace_debug);
3955 defsubr (&Sbacktrace);
3956 defsubr (&Sbacktrace_frame);
3957 defsubr (&Sbacktrace_eval);
3958 defsubr (&Sbacktrace__locals);
3959 defsubr (&Sspecial_variable_p);
3960 defsubr (&Sfunctionp);