Merge branch 'master' into comment-cache
[emacs.git] / src / eval.c
blob22b02b495211df5e944c36cf1f2f9098fe56a78b
1 /* Evaluator for GNU Emacs Lisp interpreter.
3 Copyright (C) 1985-1987, 1993-1995, 1999-2017 Free Software Foundation,
4 Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
23 #include <limits.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include "lisp.h"
27 #include "blockinput.h"
28 #include "commands.h"
29 #include "keyboard.h"
30 #include "dispextern.h"
31 #include "buffer.h"
33 /* Chain of condition and catch handlers currently in effect. */
35 /* struct handler *handlerlist; */
37 /* Non-nil means record all fset's and provide's, to be undone
38 if the file being autoloaded is not fully loaded.
39 They are recorded by being consed onto the front of Vautoload_queue:
40 (FUN . ODEF) for a defun, (0 . OFEATURES) for a provide. */
42 Lisp_Object Vautoload_queue;
44 /* This holds either the symbol `run-hooks' or nil.
45 It is nil at an early stage of startup, and when Emacs
46 is shutting down. */
47 Lisp_Object Vrun_hooks;
49 /* The commented-out variables below are macros defined in thread.h. */
51 /* Current number of specbindings allocated in specpdl, not counting
52 the dummy entry specpdl[-1]. */
54 /* ptrdiff_t specpdl_size; */
56 /* Pointer to beginning of specpdl. A dummy entry specpdl[-1] exists
57 only so that its address can be taken. */
59 /* union specbinding *specpdl; */
61 /* Pointer to first unused element in specpdl. */
63 /* union specbinding *specpdl_ptr; */
65 /* Depth in Lisp evaluations and function calls. */
67 /* static EMACS_INT lisp_eval_depth; */
69 /* The value of num_nonmacro_input_events as of the last time we
70 started to enter the debugger. If we decide to enter the debugger
71 again when this is still equal to num_nonmacro_input_events, then we
72 know that the debugger itself has an error, and we should just
73 signal the error instead of entering an infinite loop of debugger
74 invocations. */
76 static EMACS_INT when_entered_debugger;
78 /* The function from which the last `signal' was called. Set in
79 Fsignal. */
80 /* FIXME: We should probably get rid of this! */
81 Lisp_Object Vsignaling_function;
83 /* If non-nil, Lisp code must not be run since some part of Emacs is in
84 an inconsistent state. Currently unused. */
85 Lisp_Object inhibit_lisp_code;
87 /* These would ordinarily be static, but they need to be visible to GDB. */
88 bool backtrace_p (union specbinding *) EXTERNALLY_VISIBLE;
89 Lisp_Object *backtrace_args (union specbinding *) EXTERNALLY_VISIBLE;
90 Lisp_Object backtrace_function (union specbinding *) EXTERNALLY_VISIBLE;
91 union specbinding *backtrace_next (union specbinding *) EXTERNALLY_VISIBLE;
92 union specbinding *backtrace_top (void) EXTERNALLY_VISIBLE;
94 static Lisp_Object funcall_lambda (Lisp_Object, ptrdiff_t, Lisp_Object *);
95 static Lisp_Object apply_lambda (Lisp_Object, Lisp_Object, ptrdiff_t);
96 static Lisp_Object lambda_arity (Lisp_Object);
98 static Lisp_Object
99 specpdl_symbol (union specbinding *pdl)
101 eassert (pdl->kind >= SPECPDL_LET);
102 return pdl->let.symbol;
105 static enum specbind_tag
106 specpdl_kind (union specbinding *pdl)
108 eassert (pdl->kind >= SPECPDL_LET);
109 return pdl->let.kind;
112 static Lisp_Object
113 specpdl_old_value (union specbinding *pdl)
115 eassert (pdl->kind >= SPECPDL_LET);
116 return pdl->let.old_value;
119 static void
120 set_specpdl_old_value (union specbinding *pdl, Lisp_Object val)
122 eassert (pdl->kind >= SPECPDL_LET);
123 pdl->let.old_value = val;
126 static Lisp_Object
127 specpdl_where (union specbinding *pdl)
129 eassert (pdl->kind > SPECPDL_LET);
130 return pdl->let.where;
133 static Lisp_Object
134 specpdl_saved_value (union specbinding *pdl)
136 eassert (pdl->kind >= SPECPDL_LET);
137 return pdl->let.saved_value;
140 static Lisp_Object
141 specpdl_arg (union specbinding *pdl)
143 eassert (pdl->kind == SPECPDL_UNWIND);
144 return pdl->unwind.arg;
147 Lisp_Object
148 backtrace_function (union specbinding *pdl)
150 eassert (pdl->kind == SPECPDL_BACKTRACE);
151 return pdl->bt.function;
154 static ptrdiff_t
155 backtrace_nargs (union specbinding *pdl)
157 eassert (pdl->kind == SPECPDL_BACKTRACE);
158 return pdl->bt.nargs;
161 Lisp_Object *
162 backtrace_args (union specbinding *pdl)
164 eassert (pdl->kind == SPECPDL_BACKTRACE);
165 return pdl->bt.args;
168 static bool
169 backtrace_debug_on_exit (union specbinding *pdl)
171 eassert (pdl->kind == SPECPDL_BACKTRACE);
172 return pdl->bt.debug_on_exit;
175 /* Functions to modify slots of backtrace records. */
177 static void
178 set_backtrace_args (union specbinding *pdl, Lisp_Object *args, ptrdiff_t nargs)
180 eassert (pdl->kind == SPECPDL_BACKTRACE);
181 pdl->bt.args = args;
182 pdl->bt.nargs = nargs;
185 static void
186 set_backtrace_debug_on_exit (union specbinding *pdl, bool doe)
188 eassert (pdl->kind == SPECPDL_BACKTRACE);
189 pdl->bt.debug_on_exit = doe;
192 /* Helper functions to scan the backtrace. */
194 bool
195 backtrace_p (union specbinding *pdl)
196 { return pdl >= specpdl; }
198 union specbinding *
199 backtrace_top (void)
201 union specbinding *pdl = specpdl_ptr - 1;
202 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
203 pdl--;
204 return pdl;
207 union specbinding *
208 backtrace_next (union specbinding *pdl)
210 pdl--;
211 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
212 pdl--;
213 return pdl;
216 /* Return a pointer to somewhere near the top of the C stack. */
217 void *
218 near_C_stack_top (void)
220 return backtrace_args (backtrace_top ());
223 void
224 init_eval_once (void)
226 enum { size = 50 };
227 union specbinding *pdlvec = xmalloc ((size + 1) * sizeof *specpdl);
228 specpdl_size = size;
229 specpdl = specpdl_ptr = pdlvec + 1;
230 /* Don't forget to update docs (lispref node "Local Variables"). */
231 max_specpdl_size = 1300; /* 1000 is not enough for CEDET's c-by.el. */
232 max_lisp_eval_depth = 800;
234 Vrun_hooks = Qnil;
237 /* static struct handler handlerlist_sentinel; */
239 void
240 init_eval (void)
242 specpdl_ptr = specpdl;
243 { /* Put a dummy catcher at top-level so that handlerlist is never NULL.
244 This is important since handlerlist->nextfree holds the freelist
245 which would otherwise leak every time we unwind back to top-level. */
246 handlerlist_sentinel = xzalloc (sizeof (struct handler));
247 handlerlist = handlerlist_sentinel->nextfree = handlerlist_sentinel;
248 struct handler *c = push_handler (Qunbound, CATCHER);
249 eassert (c == handlerlist_sentinel);
250 handlerlist_sentinel->nextfree = NULL;
251 handlerlist_sentinel->next = NULL;
253 Vquit_flag = Qnil;
254 debug_on_next_call = 0;
255 lisp_eval_depth = 0;
256 /* This is less than the initial value of num_nonmacro_input_events. */
257 when_entered_debugger = -1;
260 /* Unwind-protect function used by call_debugger. */
262 static void
263 restore_stack_limits (Lisp_Object data)
265 max_specpdl_size = XINT (XCAR (data));
266 max_lisp_eval_depth = XINT (XCDR (data));
269 static void grow_specpdl (void);
271 /* Call the Lisp debugger, giving it argument ARG. */
273 Lisp_Object
274 call_debugger (Lisp_Object arg)
276 bool debug_while_redisplaying;
277 ptrdiff_t count = SPECPDL_INDEX ();
278 Lisp_Object val;
279 EMACS_INT old_depth = max_lisp_eval_depth;
280 /* Do not allow max_specpdl_size less than actual depth (Bug#16603). */
281 EMACS_INT old_max = max (max_specpdl_size, count);
283 if (lisp_eval_depth + 40 > max_lisp_eval_depth)
284 max_lisp_eval_depth = lisp_eval_depth + 40;
286 /* While debugging Bug#16603, previous value of 100 was found
287 too small to avoid specpdl overflow in the debugger itself. */
288 if (max_specpdl_size - 200 < count)
289 max_specpdl_size = count + 200;
291 if (old_max == count)
293 /* We can enter the debugger due to specpdl overflow (Bug#16603). */
294 specpdl_ptr--;
295 grow_specpdl ();
298 /* Restore limits after leaving the debugger. */
299 record_unwind_protect (restore_stack_limits,
300 Fcons (make_number (old_max),
301 make_number (old_depth)));
303 #ifdef HAVE_WINDOW_SYSTEM
304 if (display_hourglass_p)
305 cancel_hourglass ();
306 #endif
308 debug_on_next_call = 0;
309 when_entered_debugger = num_nonmacro_input_events;
311 /* Resetting redisplaying_p to 0 makes sure that debug output is
312 displayed if the debugger is invoked during redisplay. */
313 debug_while_redisplaying = redisplaying_p;
314 redisplaying_p = 0;
315 specbind (intern ("debugger-may-continue"),
316 debug_while_redisplaying ? Qnil : Qt);
317 specbind (Qinhibit_redisplay, Qnil);
318 specbind (Qinhibit_debugger, Qt);
320 /* If we are debugging an error while `inhibit-changing-match-data'
321 is bound to non-nil (e.g., within a call to `string-match-p'),
322 then make sure debugger code can still use match data. */
323 specbind (Qinhibit_changing_match_data, Qnil);
325 #if 0 /* Binding this prevents execution of Lisp code during
326 redisplay, which necessarily leads to display problems. */
327 specbind (Qinhibit_eval_during_redisplay, Qt);
328 #endif
330 val = apply1 (Vdebugger, arg);
332 /* Interrupting redisplay and resuming it later is not safe under
333 all circumstances. So, when the debugger returns, abort the
334 interrupted redisplay by going back to the top-level. */
335 if (debug_while_redisplaying)
336 Ftop_level ();
338 return unbind_to (count, val);
341 static void
342 do_debug_on_call (Lisp_Object code, ptrdiff_t count)
344 debug_on_next_call = 0;
345 set_backtrace_debug_on_exit (specpdl + count, true);
346 call_debugger (list1 (code));
349 /* NOTE!!! Every function that can call EVAL must protect its args
350 and temporaries from garbage collection while it needs them.
351 The definition of `For' shows what you have to do. */
353 DEFUN ("or", For, Sor, 0, UNEVALLED, 0,
354 doc: /* Eval args until one of them yields non-nil, then return that value.
355 The remaining args are not evalled at all.
356 If all args return nil, return nil.
357 usage: (or CONDITIONS...) */)
358 (Lisp_Object args)
360 Lisp_Object val = Qnil;
362 while (CONSP (args))
364 val = eval_sub (XCAR (args));
365 if (!NILP (val))
366 break;
367 args = XCDR (args);
370 return val;
373 DEFUN ("and", Fand, Sand, 0, UNEVALLED, 0,
374 doc: /* Eval args until one of them yields nil, then return nil.
375 The remaining args are not evalled at all.
376 If no arg yields nil, return the last arg's value.
377 usage: (and CONDITIONS...) */)
378 (Lisp_Object args)
380 Lisp_Object val = Qt;
382 while (CONSP (args))
384 val = eval_sub (XCAR (args));
385 if (NILP (val))
386 break;
387 args = XCDR (args);
390 return val;
393 DEFUN ("if", Fif, Sif, 2, UNEVALLED, 0,
394 doc: /* If COND yields non-nil, do THEN, else do ELSE...
395 Returns the value of THEN or the value of the last of the ELSE's.
396 THEN must be one expression, but ELSE... can be zero or more expressions.
397 If COND yields nil, and there are no ELSE's, the value is nil.
398 usage: (if COND THEN ELSE...) */)
399 (Lisp_Object args)
401 Lisp_Object cond;
403 cond = eval_sub (XCAR (args));
405 if (!NILP (cond))
406 return eval_sub (Fcar (XCDR (args)));
407 return Fprogn (XCDR (XCDR (args)));
410 DEFUN ("cond", Fcond, Scond, 0, UNEVALLED, 0,
411 doc: /* Try each clause until one succeeds.
412 Each clause looks like (CONDITION BODY...). CONDITION is evaluated
413 and, if the value is non-nil, this clause succeeds:
414 then the expressions in BODY are evaluated and the last one's
415 value is the value of the cond-form.
416 If a clause has one element, as in (CONDITION), then the cond-form
417 returns CONDITION's value, if that is non-nil.
418 If no clause succeeds, cond returns nil.
419 usage: (cond CLAUSES...) */)
420 (Lisp_Object args)
422 Lisp_Object val = args;
424 while (CONSP (args))
426 Lisp_Object clause = XCAR (args);
427 val = eval_sub (Fcar (clause));
428 if (!NILP (val))
430 if (!NILP (XCDR (clause)))
431 val = Fprogn (XCDR (clause));
432 break;
434 args = XCDR (args);
437 return val;
440 DEFUN ("progn", Fprogn, Sprogn, 0, UNEVALLED, 0,
441 doc: /* Eval BODY forms sequentially and return value of last one.
442 usage: (progn BODY...) */)
443 (Lisp_Object body)
445 Lisp_Object val = Qnil;
447 while (CONSP (body))
449 val = eval_sub (XCAR (body));
450 body = XCDR (body);
453 return val;
456 /* Evaluate BODY sequentially, discarding its value. */
458 void
459 prog_ignore (Lisp_Object body)
461 Fprogn (body);
464 DEFUN ("prog1", Fprog1, Sprog1, 1, UNEVALLED, 0,
465 doc: /* Eval FIRST and BODY sequentially; return value from FIRST.
466 The value of FIRST is saved during the evaluation of the remaining args,
467 whose values are discarded.
468 usage: (prog1 FIRST BODY...) */)
469 (Lisp_Object args)
471 Lisp_Object val = eval_sub (XCAR (args));
472 prog_ignore (XCDR (args));
473 return val;
476 DEFUN ("prog2", Fprog2, Sprog2, 2, UNEVALLED, 0,
477 doc: /* Eval FORM1, FORM2 and BODY sequentially; return value from FORM2.
478 The value of FORM2 is saved during the evaluation of the
479 remaining args, whose values are discarded.
480 usage: (prog2 FORM1 FORM2 BODY...) */)
481 (Lisp_Object args)
483 eval_sub (XCAR (args));
484 return Fprog1 (XCDR (args));
487 DEFUN ("setq", Fsetq, Ssetq, 0, UNEVALLED, 0,
488 doc: /* Set each SYM to the value of its VAL.
489 The symbols SYM are variables; they are literal (not evaluated).
490 The values VAL are expressions; they are evaluated.
491 Thus, (setq x (1+ y)) sets `x' to the value of `(1+ y)'.
492 The second VAL is not computed until after the first SYM is set, and so on;
493 each VAL can use the new value of variables set earlier in the `setq'.
494 The return value of the `setq' form is the value of the last VAL.
495 usage: (setq [SYM VAL]...) */)
496 (Lisp_Object args)
498 Lisp_Object val, sym, lex_binding;
500 val = args;
501 if (CONSP (args))
503 Lisp_Object args_left = args;
504 Lisp_Object numargs = Flength (args);
506 if (XINT (numargs) & 1)
507 xsignal2 (Qwrong_number_of_arguments, Qsetq, numargs);
511 val = eval_sub (Fcar (XCDR (args_left)));
512 sym = XCAR (args_left);
514 /* Like for eval_sub, we do not check declared_special here since
515 it's been done when let-binding. */
516 if (!NILP (Vinternal_interpreter_environment) /* Mere optimization! */
517 && SYMBOLP (sym)
518 && !NILP (lex_binding
519 = Fassq (sym, Vinternal_interpreter_environment)))
520 XSETCDR (lex_binding, val); /* SYM is lexically bound. */
521 else
522 Fset (sym, val); /* SYM is dynamically bound. */
524 args_left = Fcdr (XCDR (args_left));
526 while (CONSP (args_left));
529 return val;
532 DEFUN ("quote", Fquote, Squote, 1, UNEVALLED, 0,
533 doc: /* Return the argument, without evaluating it. `(quote x)' yields `x'.
534 Warning: `quote' does not construct its return value, but just returns
535 the value that was pre-constructed by the Lisp reader (see info node
536 `(elisp)Printed Representation').
537 This means that \\='(a . b) is not identical to (cons \\='a \\='b): the former
538 does not cons. Quoting should be reserved for constants that will
539 never be modified by side-effects, unless you like self-modifying code.
540 See the common pitfall in info node `(elisp)Rearrangement' for an example
541 of unexpected results when a quoted object is modified.
542 usage: (quote ARG) */)
543 (Lisp_Object args)
545 if (CONSP (XCDR (args)))
546 xsignal2 (Qwrong_number_of_arguments, Qquote, Flength (args));
547 return XCAR (args);
550 DEFUN ("function", Ffunction, Sfunction, 1, UNEVALLED, 0,
551 doc: /* Like `quote', but preferred for objects which are functions.
552 In byte compilation, `function' causes its argument to be compiled.
553 `quote' cannot do that.
554 usage: (function ARG) */)
555 (Lisp_Object args)
557 Lisp_Object quoted = XCAR (args);
559 if (CONSP (XCDR (args)))
560 xsignal2 (Qwrong_number_of_arguments, Qfunction, Flength (args));
562 if (!NILP (Vinternal_interpreter_environment)
563 && CONSP (quoted)
564 && EQ (XCAR (quoted), Qlambda))
565 { /* This is a lambda expression within a lexical environment;
566 return an interpreted closure instead of a simple lambda. */
567 Lisp_Object cdr = XCDR (quoted);
568 Lisp_Object tmp = cdr;
569 if (CONSP (tmp)
570 && (tmp = XCDR (tmp), CONSP (tmp))
571 && (tmp = XCAR (tmp), CONSP (tmp))
572 && (EQ (QCdocumentation, XCAR (tmp))))
573 { /* Handle the special (:documentation <form>) to build the docstring
574 dynamically. */
575 Lisp_Object docstring = eval_sub (Fcar (XCDR (tmp)));
576 CHECK_STRING (docstring);
577 cdr = Fcons (XCAR (cdr), Fcons (docstring, XCDR (XCDR (cdr))));
579 return Fcons (Qclosure, Fcons (Vinternal_interpreter_environment,
580 cdr));
582 else
583 /* Simply quote the argument. */
584 return quoted;
588 DEFUN ("defvaralias", Fdefvaralias, Sdefvaralias, 2, 3, 0,
589 doc: /* Make NEW-ALIAS a variable alias for symbol BASE-VARIABLE.
590 Aliased variables always have the same value; setting one sets the other.
591 Third arg DOCSTRING, if non-nil, is documentation for NEW-ALIAS. If it is
592 omitted or nil, NEW-ALIAS gets the documentation string of BASE-VARIABLE,
593 or of the variable at the end of the chain of aliases, if BASE-VARIABLE is
594 itself an alias. If NEW-ALIAS is bound, and BASE-VARIABLE is not,
595 then the value of BASE-VARIABLE is set to that of NEW-ALIAS.
596 The return value is BASE-VARIABLE. */)
597 (Lisp_Object new_alias, Lisp_Object base_variable, Lisp_Object docstring)
599 struct Lisp_Symbol *sym;
601 CHECK_SYMBOL (new_alias);
602 CHECK_SYMBOL (base_variable);
604 if (SYMBOL_CONSTANT_P (new_alias))
605 /* Making it an alias effectively changes its value. */
606 error ("Cannot make a constant an alias");
608 sym = XSYMBOL (new_alias);
610 switch (sym->redirect)
612 case SYMBOL_FORWARDED:
613 error ("Cannot make an internal variable an alias");
614 case SYMBOL_LOCALIZED:
615 error ("Don't know how to make a localized variable an alias");
616 case SYMBOL_PLAINVAL:
617 case SYMBOL_VARALIAS:
618 break;
619 default:
620 emacs_abort ();
623 /* http://lists.gnu.org/archive/html/emacs-devel/2008-04/msg00834.html
624 If n_a is bound, but b_v is not, set the value of b_v to n_a,
625 so that old-code that affects n_a before the aliasing is setup
626 still works. */
627 if (NILP (Fboundp (base_variable)))
628 set_internal (base_variable, find_symbol_value (new_alias),
629 Qnil, SET_INTERNAL_BIND);
631 union specbinding *p;
633 for (p = specpdl_ptr; p > specpdl; )
634 if ((--p)->kind >= SPECPDL_LET
635 && (EQ (new_alias, specpdl_symbol (p))))
636 error ("Don't know how to make a let-bound variable an alias");
639 if (sym->trapped_write == SYMBOL_TRAPPED_WRITE)
640 notify_variable_watchers (new_alias, base_variable, Qdefvaralias, Qnil);
642 sym->declared_special = 1;
643 XSYMBOL (base_variable)->declared_special = 1;
644 sym->redirect = SYMBOL_VARALIAS;
645 SET_SYMBOL_ALIAS (sym, XSYMBOL (base_variable));
646 sym->trapped_write = XSYMBOL (base_variable)->trapped_write;
647 LOADHIST_ATTACH (new_alias);
648 /* Even if docstring is nil: remove old docstring. */
649 Fput (new_alias, Qvariable_documentation, docstring);
651 return base_variable;
654 static union specbinding *
655 default_toplevel_binding (Lisp_Object symbol)
657 union specbinding *binding = NULL;
658 union specbinding *pdl = specpdl_ptr;
659 while (pdl > specpdl)
661 switch ((--pdl)->kind)
663 case SPECPDL_LET_DEFAULT:
664 case SPECPDL_LET:
665 if (EQ (specpdl_symbol (pdl), symbol))
666 binding = pdl;
667 break;
669 case SPECPDL_UNWIND:
670 case SPECPDL_UNWIND_PTR:
671 case SPECPDL_UNWIND_INT:
672 case SPECPDL_UNWIND_VOID:
673 case SPECPDL_BACKTRACE:
674 case SPECPDL_LET_LOCAL:
675 break;
677 default:
678 emacs_abort ();
681 return binding;
684 DEFUN ("default-toplevel-value", Fdefault_toplevel_value, Sdefault_toplevel_value, 1, 1, 0,
685 doc: /* Return SYMBOL's toplevel default value.
686 "Toplevel" means outside of any let binding. */)
687 (Lisp_Object symbol)
689 union specbinding *binding = default_toplevel_binding (symbol);
690 Lisp_Object value
691 = binding ? specpdl_old_value (binding) : Fdefault_value (symbol);
692 if (!EQ (value, Qunbound))
693 return value;
694 xsignal1 (Qvoid_variable, symbol);
697 DEFUN ("set-default-toplevel-value", Fset_default_toplevel_value,
698 Sset_default_toplevel_value, 2, 2, 0,
699 doc: /* Set SYMBOL's toplevel default value to VALUE.
700 "Toplevel" means outside of any let binding. */)
701 (Lisp_Object symbol, Lisp_Object value)
703 union specbinding *binding = default_toplevel_binding (symbol);
704 if (binding)
705 set_specpdl_old_value (binding, value);
706 else
707 Fset_default (symbol, value);
708 return Qnil;
711 DEFUN ("defvar", Fdefvar, Sdefvar, 1, UNEVALLED, 0,
712 doc: /* Define SYMBOL as a variable, and return SYMBOL.
713 You are not required to define a variable in order to use it, but
714 defining it lets you supply an initial value and documentation, which
715 can be referred to by the Emacs help facilities and other programming
716 tools. The `defvar' form also declares the variable as \"special\",
717 so that it is always dynamically bound even if `lexical-binding' is t.
719 If SYMBOL's value is void and the optional argument INITVALUE is
720 provided, INITVALUE is evaluated and the result used to set SYMBOL's
721 value. If SYMBOL is buffer-local, its default value is what is set;
722 buffer-local values are not affected. If INITVALUE is missing,
723 SYMBOL's value is not set.
725 If SYMBOL has a local binding, then this form affects the local
726 binding. This is usually not what you want. Thus, if you need to
727 load a file defining variables, with this form or with `defconst' or
728 `defcustom', you should always load that file _outside_ any bindings
729 for these variables. (`defconst' and `defcustom' behave similarly in
730 this respect.)
732 The optional argument DOCSTRING is a documentation string for the
733 variable.
735 To define a user option, use `defcustom' instead of `defvar'.
736 usage: (defvar SYMBOL &optional INITVALUE DOCSTRING) */)
737 (Lisp_Object args)
739 Lisp_Object sym, tem, tail;
741 sym = XCAR (args);
742 tail = XCDR (args);
744 if (CONSP (tail))
746 if (CONSP (XCDR (tail)) && CONSP (XCDR (XCDR (tail))))
747 error ("Too many arguments");
749 tem = Fdefault_boundp (sym);
751 /* Do it before evaluating the initial value, for self-references. */
752 XSYMBOL (sym)->declared_special = 1;
754 if (NILP (tem))
755 Fset_default (sym, eval_sub (XCAR (tail)));
756 else
757 { /* Check if there is really a global binding rather than just a let
758 binding that shadows the global unboundness of the var. */
759 union specbinding *binding = default_toplevel_binding (sym);
760 if (binding && EQ (specpdl_old_value (binding), Qunbound))
762 set_specpdl_old_value (binding, eval_sub (XCAR (tail)));
765 tail = XCDR (tail);
766 tem = Fcar (tail);
767 if (!NILP (tem))
769 if (!NILP (Vpurify_flag))
770 tem = Fpurecopy (tem);
771 Fput (sym, Qvariable_documentation, tem);
773 LOADHIST_ATTACH (sym);
775 else if (!NILP (Vinternal_interpreter_environment)
776 && !XSYMBOL (sym)->declared_special)
777 /* A simple (defvar foo) with lexical scoping does "nothing" except
778 declare that var to be dynamically scoped *locally* (i.e. within
779 the current file or let-block). */
780 Vinternal_interpreter_environment
781 = Fcons (sym, Vinternal_interpreter_environment);
782 else
784 /* Simple (defvar <var>) should not count as a definition at all.
785 It could get in the way of other definitions, and unloading this
786 package could try to make the variable unbound. */
789 return sym;
792 DEFUN ("defconst", Fdefconst, Sdefconst, 2, UNEVALLED, 0,
793 doc: /* Define SYMBOL as a constant variable.
794 This declares that neither programs nor users should ever change the
795 value. This constancy is not actually enforced by Emacs Lisp, but
796 SYMBOL is marked as a special variable so that it is never lexically
797 bound.
799 The `defconst' form always sets the value of SYMBOL to the result of
800 evalling INITVALUE. If SYMBOL is buffer-local, its default value is
801 what is set; buffer-local values are not affected. If SYMBOL has a
802 local binding, then this form sets the local binding's value.
803 However, you should normally not make local bindings for variables
804 defined with this form.
806 The optional DOCSTRING specifies the variable's documentation string.
807 usage: (defconst SYMBOL INITVALUE [DOCSTRING]) */)
808 (Lisp_Object args)
810 Lisp_Object sym, tem;
812 sym = XCAR (args);
813 if (CONSP (Fcdr (XCDR (XCDR (args)))))
814 error ("Too many arguments");
816 tem = eval_sub (Fcar (XCDR (args)));
817 if (!NILP (Vpurify_flag))
818 tem = Fpurecopy (tem);
819 Fset_default (sym, tem);
820 XSYMBOL (sym)->declared_special = 1;
821 tem = Fcar (XCDR (XCDR (args)));
822 if (!NILP (tem))
824 if (!NILP (Vpurify_flag))
825 tem = Fpurecopy (tem);
826 Fput (sym, Qvariable_documentation, tem);
828 Fput (sym, Qrisky_local_variable, Qt);
829 LOADHIST_ATTACH (sym);
830 return sym;
833 /* Make SYMBOL lexically scoped. */
834 DEFUN ("internal-make-var-non-special", Fmake_var_non_special,
835 Smake_var_non_special, 1, 1, 0,
836 doc: /* Internal function. */)
837 (Lisp_Object symbol)
839 CHECK_SYMBOL (symbol);
840 XSYMBOL (symbol)->declared_special = 0;
841 return Qnil;
845 DEFUN ("let*", FletX, SletX, 1, UNEVALLED, 0,
846 doc: /* Bind variables according to VARLIST then eval BODY.
847 The value of the last form in BODY is returned.
848 Each element of VARLIST is a symbol (which is bound to nil)
849 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
850 Each VALUEFORM can refer to the symbols already bound by this VARLIST.
851 usage: (let* VARLIST BODY...) */)
852 (Lisp_Object args)
854 Lisp_Object varlist, var, val, elt, lexenv;
855 ptrdiff_t count = SPECPDL_INDEX ();
857 lexenv = Vinternal_interpreter_environment;
859 for (varlist = XCAR (args); CONSP (varlist); varlist = XCDR (varlist))
861 maybe_quit ();
863 elt = XCAR (varlist);
864 if (SYMBOLP (elt))
866 var = elt;
867 val = Qnil;
869 else if (! NILP (Fcdr (Fcdr (elt))))
870 signal_error ("`let' bindings can have only one value-form", elt);
871 else
873 var = Fcar (elt);
874 val = eval_sub (Fcar (Fcdr (elt)));
877 if (!NILP (lexenv) && SYMBOLP (var)
878 && !XSYMBOL (var)->declared_special
879 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
880 /* Lexically bind VAR by adding it to the interpreter's binding
881 alist. */
883 Lisp_Object newenv
884 = Fcons (Fcons (var, val), Vinternal_interpreter_environment);
885 if (EQ (Vinternal_interpreter_environment, lexenv))
886 /* Save the old lexical environment on the specpdl stack,
887 but only for the first lexical binding, since we'll never
888 need to revert to one of the intermediate ones. */
889 specbind (Qinternal_interpreter_environment, newenv);
890 else
891 Vinternal_interpreter_environment = newenv;
893 else
894 specbind (var, val);
896 CHECK_LIST_END (varlist, XCAR (args));
898 val = Fprogn (XCDR (args));
899 return unbind_to (count, val);
902 DEFUN ("let", Flet, Slet, 1, UNEVALLED, 0,
903 doc: /* Bind variables according to VARLIST then eval BODY.
904 The value of the last form in BODY is returned.
905 Each element of VARLIST is a symbol (which is bound to nil)
906 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
907 All the VALUEFORMs are evalled before any symbols are bound.
908 usage: (let VARLIST BODY...) */)
909 (Lisp_Object args)
911 Lisp_Object *temps, tem, lexenv;
912 Lisp_Object elt, varlist;
913 ptrdiff_t count = SPECPDL_INDEX ();
914 ptrdiff_t argnum;
915 USE_SAFE_ALLOCA;
917 varlist = XCAR (args);
918 CHECK_LIST (varlist);
920 /* Make space to hold the values to give the bound variables. */
921 elt = Flength (varlist);
922 SAFE_ALLOCA_LISP (temps, XFASTINT (elt));
924 /* Compute the values and store them in `temps'. */
926 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
928 maybe_quit ();
929 elt = XCAR (varlist);
930 if (SYMBOLP (elt))
931 temps [argnum++] = Qnil;
932 else if (! NILP (Fcdr (Fcdr (elt))))
933 signal_error ("`let' bindings can have only one value-form", elt);
934 else
935 temps [argnum++] = eval_sub (Fcar (Fcdr (elt)));
938 lexenv = Vinternal_interpreter_environment;
940 varlist = XCAR (args);
941 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
943 Lisp_Object var;
945 elt = XCAR (varlist);
946 var = SYMBOLP (elt) ? elt : Fcar (elt);
947 tem = temps[argnum++];
949 if (!NILP (lexenv) && SYMBOLP (var)
950 && !XSYMBOL (var)->declared_special
951 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
952 /* Lexically bind VAR by adding it to the lexenv alist. */
953 lexenv = Fcons (Fcons (var, tem), lexenv);
954 else
955 /* Dynamically bind VAR. */
956 specbind (var, tem);
959 if (!EQ (lexenv, Vinternal_interpreter_environment))
960 /* Instantiate a new lexical environment. */
961 specbind (Qinternal_interpreter_environment, lexenv);
963 elt = Fprogn (XCDR (args));
964 SAFE_FREE ();
965 return unbind_to (count, elt);
968 DEFUN ("while", Fwhile, Swhile, 1, UNEVALLED, 0,
969 doc: /* If TEST yields non-nil, eval BODY... and repeat.
970 The order of execution is thus TEST, BODY, TEST, BODY and so on
971 until TEST returns nil.
972 usage: (while TEST BODY...) */)
973 (Lisp_Object args)
975 Lisp_Object test, body;
977 test = XCAR (args);
978 body = XCDR (args);
979 while (!NILP (eval_sub (test)))
981 maybe_quit ();
982 prog_ignore (body);
985 return Qnil;
988 DEFUN ("macroexpand", Fmacroexpand, Smacroexpand, 1, 2, 0,
989 doc: /* Return result of expanding macros at top level of FORM.
990 If FORM is not a macro call, it is returned unchanged.
991 Otherwise, the macro is expanded and the expansion is considered
992 in place of FORM. When a non-macro-call results, it is returned.
994 The second optional arg ENVIRONMENT specifies an environment of macro
995 definitions to shadow the loaded ones for use in file byte-compilation. */)
996 (Lisp_Object form, Lisp_Object environment)
998 /* With cleanups from Hallvard Furuseth. */
999 register Lisp_Object expander, sym, def, tem;
1001 while (1)
1003 /* Come back here each time we expand a macro call,
1004 in case it expands into another macro call. */
1005 if (!CONSP (form))
1006 break;
1007 /* Set SYM, give DEF and TEM right values in case SYM is not a symbol. */
1008 def = sym = XCAR (form);
1009 tem = Qnil;
1010 /* Trace symbols aliases to other symbols
1011 until we get a symbol that is not an alias. */
1012 while (SYMBOLP (def))
1014 maybe_quit ();
1015 sym = def;
1016 tem = Fassq (sym, environment);
1017 if (NILP (tem))
1019 def = XSYMBOL (sym)->function;
1020 if (!NILP (def))
1021 continue;
1023 break;
1025 /* Right now TEM is the result from SYM in ENVIRONMENT,
1026 and if TEM is nil then DEF is SYM's function definition. */
1027 if (NILP (tem))
1029 /* SYM is not mentioned in ENVIRONMENT.
1030 Look at its function definition. */
1031 def = Fautoload_do_load (def, sym, Qmacro);
1032 if (!CONSP (def))
1033 /* Not defined or definition not suitable. */
1034 break;
1035 if (!EQ (XCAR (def), Qmacro))
1036 break;
1037 else expander = XCDR (def);
1039 else
1041 expander = XCDR (tem);
1042 if (NILP (expander))
1043 break;
1046 Lisp_Object newform = apply1 (expander, XCDR (form));
1047 if (EQ (form, newform))
1048 break;
1049 else
1050 form = newform;
1053 return form;
1056 DEFUN ("catch", Fcatch, Scatch, 1, UNEVALLED, 0,
1057 doc: /* Eval BODY allowing nonlocal exits using `throw'.
1058 TAG is evalled to get the tag to use; it must not be nil.
1060 Then the BODY is executed.
1061 Within BODY, a call to `throw' with the same TAG exits BODY and this `catch'.
1062 If no throw happens, `catch' returns the value of the last BODY form.
1063 If a throw happens, it specifies the value to return from `catch'.
1064 usage: (catch TAG BODY...) */)
1065 (Lisp_Object args)
1067 Lisp_Object tag = eval_sub (XCAR (args));
1068 return internal_catch (tag, Fprogn, XCDR (args));
1071 /* Assert that E is true, but do not evaluate E. Use this instead of
1072 eassert (E) when E contains variables that might be clobbered by a
1073 longjmp. */
1075 #define clobbered_eassert(E) verify (sizeof (E) != 0)
1077 /* Set up a catch, then call C function FUNC on argument ARG.
1078 FUNC should return a Lisp_Object.
1079 This is how catches are done from within C code. */
1081 Lisp_Object
1082 internal_catch (Lisp_Object tag,
1083 Lisp_Object (*func) (Lisp_Object), Lisp_Object arg)
1085 /* This structure is made part of the chain `catchlist'. */
1086 struct handler *c = push_handler (tag, CATCHER);
1088 /* Call FUNC. */
1089 if (! sys_setjmp (c->jmp))
1091 Lisp_Object val = func (arg);
1092 eassert (handlerlist == c);
1093 handlerlist = c->next;
1094 return val;
1096 else
1097 { /* Throw works by a longjmp that comes right here. */
1098 Lisp_Object val = handlerlist->val;
1099 clobbered_eassert (handlerlist == c);
1100 handlerlist = handlerlist->next;
1101 return val;
1105 /* Unwind the specbind, catch, and handler stacks back to CATCH, and
1106 jump to that CATCH, returning VALUE as the value of that catch.
1108 This is the guts of Fthrow and Fsignal; they differ only in the way
1109 they choose the catch tag to throw to. A catch tag for a
1110 condition-case form has a TAG of Qnil.
1112 Before each catch is discarded, unbind all special bindings and
1113 execute all unwind-protect clauses made above that catch. Unwind
1114 the handler stack as we go, so that the proper handlers are in
1115 effect for each unwind-protect clause we run. At the end, restore
1116 some static info saved in CATCH, and longjmp to the location
1117 specified there.
1119 This is used for correct unwinding in Fthrow and Fsignal. */
1121 static _Noreturn void
1122 unwind_to_catch (struct handler *catch, Lisp_Object value)
1124 bool last_time;
1126 eassert (catch->next);
1128 /* Save the value in the tag. */
1129 catch->val = value;
1131 /* Restore certain special C variables. */
1132 set_poll_suppress_count (catch->poll_suppress_count);
1133 unblock_input_to (catch->interrupt_input_blocked);
1137 /* Unwind the specpdl stack, and then restore the proper set of
1138 handlers. */
1139 unbind_to (handlerlist->pdlcount, Qnil);
1140 last_time = handlerlist == catch;
1141 if (! last_time)
1142 handlerlist = handlerlist->next;
1144 while (! last_time);
1146 eassert (handlerlist == catch);
1148 lisp_eval_depth = catch->f_lisp_eval_depth;
1150 sys_longjmp (catch->jmp, 1);
1153 DEFUN ("throw", Fthrow, Sthrow, 2, 2, 0,
1154 doc: /* Throw to the catch for TAG and return VALUE from it.
1155 Both TAG and VALUE are evalled. */
1156 attributes: noreturn)
1157 (register Lisp_Object tag, Lisp_Object value)
1159 struct handler *c;
1161 if (!NILP (tag))
1162 for (c = handlerlist; c; c = c->next)
1164 if (c->type == CATCHER_ALL)
1165 unwind_to_catch (c, Fcons (tag, value));
1166 if (c->type == CATCHER && EQ (c->tag_or_ch, tag))
1167 unwind_to_catch (c, value);
1169 xsignal2 (Qno_catch, tag, value);
1173 DEFUN ("unwind-protect", Funwind_protect, Sunwind_protect, 1, UNEVALLED, 0,
1174 doc: /* Do BODYFORM, protecting with UNWINDFORMS.
1175 If BODYFORM completes normally, its value is returned
1176 after executing the UNWINDFORMS.
1177 If BODYFORM exits nonlocally, the UNWINDFORMS are executed anyway.
1178 usage: (unwind-protect BODYFORM UNWINDFORMS...) */)
1179 (Lisp_Object args)
1181 Lisp_Object val;
1182 ptrdiff_t count = SPECPDL_INDEX ();
1184 record_unwind_protect (prog_ignore, XCDR (args));
1185 val = eval_sub (XCAR (args));
1186 return unbind_to (count, val);
1189 DEFUN ("condition-case", Fcondition_case, Scondition_case, 2, UNEVALLED, 0,
1190 doc: /* Regain control when an error is signaled.
1191 Executes BODYFORM and returns its value if no error happens.
1192 Each element of HANDLERS looks like (CONDITION-NAME BODY...)
1193 where the BODY is made of Lisp expressions.
1195 A handler is applicable to an error
1196 if CONDITION-NAME is one of the error's condition names.
1197 If an error happens, the first applicable handler is run.
1199 The car of a handler may be a list of condition names instead of a
1200 single condition name; then it handles all of them. If the special
1201 condition name `debug' is present in this list, it allows another
1202 condition in the list to run the debugger if `debug-on-error' and the
1203 other usual mechanisms says it should (otherwise, `condition-case'
1204 suppresses the debugger).
1206 When a handler handles an error, control returns to the `condition-case'
1207 and it executes the handler's BODY...
1208 with VAR bound to (ERROR-SYMBOL . SIGNAL-DATA) from the error.
1209 \(If VAR is nil, the handler can't access that information.)
1210 Then the value of the last BODY form is returned from the `condition-case'
1211 expression.
1213 See also the function `signal' for more info.
1214 usage: (condition-case VAR BODYFORM &rest HANDLERS) */)
1215 (Lisp_Object args)
1217 Lisp_Object var = XCAR (args);
1218 Lisp_Object bodyform = XCAR (XCDR (args));
1219 Lisp_Object handlers = XCDR (XCDR (args));
1221 return internal_lisp_condition_case (var, bodyform, handlers);
1224 /* Like Fcondition_case, but the args are separate
1225 rather than passed in a list. Used by Fbyte_code. */
1227 Lisp_Object
1228 internal_lisp_condition_case (volatile Lisp_Object var, Lisp_Object bodyform,
1229 Lisp_Object handlers)
1231 Lisp_Object val;
1232 struct handler *oldhandlerlist = handlerlist;
1233 int clausenb = 0;
1235 CHECK_SYMBOL (var);
1237 for (val = handlers; CONSP (val); val = XCDR (val))
1239 Lisp_Object tem = XCAR (val);
1240 clausenb++;
1241 if (! (NILP (tem)
1242 || (CONSP (tem)
1243 && (SYMBOLP (XCAR (tem))
1244 || CONSP (XCAR (tem))))))
1245 error ("Invalid condition handler: %s",
1246 SDATA (Fprin1_to_string (tem, Qt)));
1249 { /* The first clause is the one that should be checked first, so it should
1250 be added to handlerlist last. So we build in `clauses' a table that
1251 contains `handlers' but in reverse order. SAFE_ALLOCA won't work
1252 here due to the setjmp, so impose a MAX_ALLOCA limit. */
1253 if (MAX_ALLOCA / word_size < clausenb)
1254 memory_full (SIZE_MAX);
1255 Lisp_Object *clauses = alloca (clausenb * sizeof *clauses);
1256 Lisp_Object *volatile clauses_volatile = clauses;
1257 int i = clausenb;
1258 for (val = handlers; CONSP (val); val = XCDR (val))
1259 clauses[--i] = XCAR (val);
1260 for (i = 0; i < clausenb; i++)
1262 Lisp_Object clause = clauses[i];
1263 Lisp_Object condition = CONSP (clause) ? XCAR (clause) : Qnil;
1264 if (!CONSP (condition))
1265 condition = Fcons (condition, Qnil);
1266 struct handler *c = push_handler (condition, CONDITION_CASE);
1267 if (sys_setjmp (c->jmp))
1269 ptrdiff_t count = SPECPDL_INDEX ();
1270 Lisp_Object val = handlerlist->val;
1271 Lisp_Object *chosen_clause = clauses_volatile;
1272 for (c = handlerlist->next; c != oldhandlerlist; c = c->next)
1273 chosen_clause++;
1274 handlerlist = oldhandlerlist;
1275 if (!NILP (var))
1277 if (!NILP (Vinternal_interpreter_environment))
1278 specbind (Qinternal_interpreter_environment,
1279 Fcons (Fcons (var, val),
1280 Vinternal_interpreter_environment));
1281 else
1282 specbind (var, val);
1284 val = Fprogn (XCDR (*chosen_clause));
1285 /* Note that this just undoes the binding of var; whoever
1286 longjumped to us unwound the stack to c.pdlcount before
1287 throwing. */
1288 if (!NILP (var))
1289 unbind_to (count, Qnil);
1290 return val;
1295 val = eval_sub (bodyform);
1296 handlerlist = oldhandlerlist;
1297 return val;
1300 /* Call the function BFUN with no arguments, catching errors within it
1301 according to HANDLERS. If there is an error, call HFUN with
1302 one argument which is the data that describes the error:
1303 (SIGNALNAME . DATA)
1305 HANDLERS can be a list of conditions to catch.
1306 If HANDLERS is Qt, catch all errors.
1307 If HANDLERS is Qerror, catch all errors
1308 but allow the debugger to run if that is enabled. */
1310 Lisp_Object
1311 internal_condition_case (Lisp_Object (*bfun) (void), Lisp_Object handlers,
1312 Lisp_Object (*hfun) (Lisp_Object))
1314 struct handler *c = push_handler (handlers, CONDITION_CASE);
1315 if (sys_setjmp (c->jmp))
1317 Lisp_Object val = handlerlist->val;
1318 clobbered_eassert (handlerlist == c);
1319 handlerlist = handlerlist->next;
1320 return hfun (val);
1322 else
1324 Lisp_Object val = bfun ();
1325 eassert (handlerlist == c);
1326 handlerlist = c->next;
1327 return val;
1331 /* Like internal_condition_case but call BFUN with ARG as its argument. */
1333 Lisp_Object
1334 internal_condition_case_1 (Lisp_Object (*bfun) (Lisp_Object), Lisp_Object arg,
1335 Lisp_Object handlers,
1336 Lisp_Object (*hfun) (Lisp_Object))
1338 struct handler *c = push_handler (handlers, CONDITION_CASE);
1339 if (sys_setjmp (c->jmp))
1341 Lisp_Object val = handlerlist->val;
1342 clobbered_eassert (handlerlist == c);
1343 handlerlist = handlerlist->next;
1344 return hfun (val);
1346 else
1348 Lisp_Object val = bfun (arg);
1349 eassert (handlerlist == c);
1350 handlerlist = c->next;
1351 return val;
1355 /* Like internal_condition_case_1 but call BFUN with ARG1 and ARG2 as
1356 its arguments. */
1358 Lisp_Object
1359 internal_condition_case_2 (Lisp_Object (*bfun) (Lisp_Object, Lisp_Object),
1360 Lisp_Object arg1,
1361 Lisp_Object arg2,
1362 Lisp_Object handlers,
1363 Lisp_Object (*hfun) (Lisp_Object))
1365 struct handler *c = push_handler (handlers, CONDITION_CASE);
1366 if (sys_setjmp (c->jmp))
1368 Lisp_Object val = handlerlist->val;
1369 clobbered_eassert (handlerlist == c);
1370 handlerlist = handlerlist->next;
1371 return hfun (val);
1373 else
1375 Lisp_Object val = bfun (arg1, arg2);
1376 eassert (handlerlist == c);
1377 handlerlist = c->next;
1378 return val;
1382 /* Like internal_condition_case but call BFUN with NARGS as first,
1383 and ARGS as second argument. */
1385 Lisp_Object
1386 internal_condition_case_n (Lisp_Object (*bfun) (ptrdiff_t, Lisp_Object *),
1387 ptrdiff_t nargs,
1388 Lisp_Object *args,
1389 Lisp_Object handlers,
1390 Lisp_Object (*hfun) (Lisp_Object err,
1391 ptrdiff_t nargs,
1392 Lisp_Object *args))
1394 struct handler *c = push_handler (handlers, CONDITION_CASE);
1395 if (sys_setjmp (c->jmp))
1397 Lisp_Object val = handlerlist->val;
1398 clobbered_eassert (handlerlist == c);
1399 handlerlist = handlerlist->next;
1400 return hfun (val, nargs, args);
1402 else
1404 Lisp_Object val = bfun (nargs, args);
1405 eassert (handlerlist == c);
1406 handlerlist = c->next;
1407 return val;
1411 struct handler *
1412 push_handler (Lisp_Object tag_ch_val, enum handlertype handlertype)
1414 struct handler *c = push_handler_nosignal (tag_ch_val, handlertype);
1415 if (!c)
1416 memory_full (sizeof *c);
1417 return c;
1420 struct handler *
1421 push_handler_nosignal (Lisp_Object tag_ch_val, enum handlertype handlertype)
1423 struct handler *c = handlerlist->nextfree;
1424 if (!c)
1426 c = malloc (sizeof *c);
1427 if (!c)
1428 return c;
1429 if (profiler_memory_running)
1430 malloc_probe (sizeof *c);
1431 c->nextfree = NULL;
1432 handlerlist->nextfree = c;
1434 c->type = handlertype;
1435 c->tag_or_ch = tag_ch_val;
1436 c->val = Qnil;
1437 c->next = handlerlist;
1438 c->f_lisp_eval_depth = lisp_eval_depth;
1439 c->pdlcount = SPECPDL_INDEX ();
1440 c->poll_suppress_count = poll_suppress_count;
1441 c->interrupt_input_blocked = interrupt_input_blocked;
1442 handlerlist = c;
1443 return c;
1447 static Lisp_Object signal_or_quit (Lisp_Object, Lisp_Object, bool);
1448 static Lisp_Object find_handler_clause (Lisp_Object, Lisp_Object);
1449 static bool maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig,
1450 Lisp_Object data);
1452 static void
1453 process_quit_flag (void)
1455 Lisp_Object flag = Vquit_flag;
1456 Vquit_flag = Qnil;
1457 if (EQ (flag, Qkill_emacs))
1458 Fkill_emacs (Qnil);
1459 if (EQ (Vthrow_on_input, flag))
1460 Fthrow (Vthrow_on_input, Qt);
1461 quit ();
1464 /* Check quit-flag and quit if it is non-nil. Typing C-g does not
1465 directly cause a quit; it only sets Vquit_flag. So the program
1466 needs to call maybe_quit at times when it is safe to quit. Every
1467 loop that might run for a long time or might not exit ought to call
1468 maybe_quit at least once, at a safe place. Unless that is
1469 impossible, of course. But it is very desirable to avoid creating
1470 loops where maybe_quit is impossible.
1472 If quit-flag is set to `kill-emacs' the SIGINT handler has received
1473 a request to exit Emacs when it is safe to do.
1475 When not quitting, process any pending signals. */
1477 void
1478 maybe_quit (void)
1480 if (!NILP (Vquit_flag) && NILP (Vinhibit_quit))
1481 process_quit_flag ();
1482 else if (pending_signals)
1483 process_pending_signals ();
1486 DEFUN ("signal", Fsignal, Ssignal, 2, 2, 0,
1487 doc: /* Signal an error. Args are ERROR-SYMBOL and associated DATA.
1488 This function does not return.
1490 An error symbol is a symbol with an `error-conditions' property
1491 that is a list of condition names.
1492 A handler for any of those names will get to handle this signal.
1493 The symbol `error' should normally be one of them.
1495 DATA should be a list. Its elements are printed as part of the error message.
1496 See Info anchor `(elisp)Definition of signal' for some details on how this
1497 error message is constructed.
1498 If the signal is handled, DATA is made available to the handler.
1499 See also the function `condition-case'. */
1500 attributes: noreturn)
1501 (Lisp_Object error_symbol, Lisp_Object data)
1503 signal_or_quit (error_symbol, data, false);
1504 eassume (false);
1507 /* Quit, in response to a keyboard quit request. */
1508 Lisp_Object
1509 quit (void)
1511 return signal_or_quit (Qquit, Qnil, true);
1514 /* Signal an error, or quit. ERROR_SYMBOL and DATA are as with Fsignal.
1515 If KEYBOARD_QUIT, this is a quit; ERROR_SYMBOL should be
1516 Qquit and DATA should be Qnil, and this function may return.
1517 Otherwise this function is like Fsignal and does not return. */
1519 static Lisp_Object
1520 signal_or_quit (Lisp_Object error_symbol, Lisp_Object data, bool keyboard_quit)
1522 /* When memory is full, ERROR-SYMBOL is nil,
1523 and DATA is (REAL-ERROR-SYMBOL . REAL-DATA).
1524 That is a special case--don't do this in other situations. */
1525 Lisp_Object conditions;
1526 Lisp_Object string;
1527 Lisp_Object real_error_symbol
1528 = (NILP (error_symbol) ? Fcar (data) : error_symbol);
1529 Lisp_Object clause = Qnil;
1530 struct handler *h;
1532 if (gc_in_progress || waiting_for_input)
1533 emacs_abort ();
1535 #if 0 /* rms: I don't know why this was here,
1536 but it is surely wrong for an error that is handled. */
1537 #ifdef HAVE_WINDOW_SYSTEM
1538 if (display_hourglass_p)
1539 cancel_hourglass ();
1540 #endif
1541 #endif
1543 /* This hook is used by edebug. */
1544 if (! NILP (Vsignal_hook_function)
1545 && ! NILP (error_symbol))
1547 /* Edebug takes care of restoring these variables when it exits. */
1548 if (lisp_eval_depth + 20 > max_lisp_eval_depth)
1549 max_lisp_eval_depth = lisp_eval_depth + 20;
1551 if (SPECPDL_INDEX () + 40 > max_specpdl_size)
1552 max_specpdl_size = SPECPDL_INDEX () + 40;
1554 call2 (Vsignal_hook_function, error_symbol, data);
1557 conditions = Fget (real_error_symbol, Qerror_conditions);
1559 /* Remember from where signal was called. Skip over the frame for
1560 `signal' itself. If a frame for `error' follows, skip that,
1561 too. Don't do this when ERROR_SYMBOL is nil, because that
1562 is a memory-full error. */
1563 Vsignaling_function = Qnil;
1564 if (!NILP (error_symbol))
1566 union specbinding *pdl = backtrace_next (backtrace_top ());
1567 if (backtrace_p (pdl) && EQ (backtrace_function (pdl), Qerror))
1568 pdl = backtrace_next (pdl);
1569 if (backtrace_p (pdl))
1570 Vsignaling_function = backtrace_function (pdl);
1573 for (h = handlerlist; h; h = h->next)
1575 if (h->type != CONDITION_CASE)
1576 continue;
1577 clause = find_handler_clause (h->tag_or_ch, conditions);
1578 if (!NILP (clause))
1579 break;
1582 if (/* Don't run the debugger for a memory-full error.
1583 (There is no room in memory to do that!) */
1584 !NILP (error_symbol)
1585 && (!NILP (Vdebug_on_signal)
1586 /* If no handler is present now, try to run the debugger. */
1587 || NILP (clause)
1588 /* A `debug' symbol in the handler list disables the normal
1589 suppression of the debugger. */
1590 || (CONSP (clause) && !NILP (Fmemq (Qdebug, clause)))
1591 /* Special handler that means "print a message and run debugger
1592 if requested". */
1593 || EQ (h->tag_or_ch, Qerror)))
1595 bool debugger_called
1596 = maybe_call_debugger (conditions, error_symbol, data);
1597 /* We can't return values to code which signaled an error, but we
1598 can continue code which has signaled a quit. */
1599 if (keyboard_quit && debugger_called && EQ (real_error_symbol, Qquit))
1600 return Qnil;
1603 if (!NILP (clause))
1605 Lisp_Object unwind_data
1606 = (NILP (error_symbol) ? data : Fcons (error_symbol, data));
1608 unwind_to_catch (h, unwind_data);
1610 else
1612 if (handlerlist != handlerlist_sentinel)
1613 /* FIXME: This will come right back here if there's no `top-level'
1614 catcher. A better solution would be to abort here, and instead
1615 add a catch-all condition handler so we never come here. */
1616 Fthrow (Qtop_level, Qt);
1619 if (! NILP (error_symbol))
1620 data = Fcons (error_symbol, data);
1622 string = Ferror_message_string (data);
1623 fatal ("%s", SDATA (string));
1626 /* Like xsignal, but takes 0, 1, 2, or 3 args instead of a list. */
1628 void
1629 xsignal0 (Lisp_Object error_symbol)
1631 xsignal (error_symbol, Qnil);
1634 void
1635 xsignal1 (Lisp_Object error_symbol, Lisp_Object arg)
1637 xsignal (error_symbol, list1 (arg));
1640 void
1641 xsignal2 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2)
1643 xsignal (error_symbol, list2 (arg1, arg2));
1646 void
1647 xsignal3 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
1649 xsignal (error_symbol, list3 (arg1, arg2, arg3));
1652 /* Signal `error' with message S, and additional arg ARG.
1653 If ARG is not a genuine list, make it a one-element list. */
1655 void
1656 signal_error (const char *s, Lisp_Object arg)
1658 Lisp_Object tortoise, hare;
1660 hare = tortoise = arg;
1661 while (CONSP (hare))
1663 hare = XCDR (hare);
1664 if (!CONSP (hare))
1665 break;
1667 hare = XCDR (hare);
1668 tortoise = XCDR (tortoise);
1670 if (EQ (hare, tortoise))
1671 break;
1674 if (!NILP (hare))
1675 arg = list1 (arg);
1677 xsignal (Qerror, Fcons (build_string (s), arg));
1681 /* Return true if LIST is a non-nil atom or
1682 a list containing one of CONDITIONS. */
1684 static bool
1685 wants_debugger (Lisp_Object list, Lisp_Object conditions)
1687 if (NILP (list))
1688 return 0;
1689 if (! CONSP (list))
1690 return 1;
1692 while (CONSP (conditions))
1694 Lisp_Object this, tail;
1695 this = XCAR (conditions);
1696 for (tail = list; CONSP (tail); tail = XCDR (tail))
1697 if (EQ (XCAR (tail), this))
1698 return 1;
1699 conditions = XCDR (conditions);
1701 return 0;
1704 /* Return true if an error with condition-symbols CONDITIONS,
1705 and described by SIGNAL-DATA, should skip the debugger
1706 according to debugger-ignored-errors. */
1708 static bool
1709 skip_debugger (Lisp_Object conditions, Lisp_Object data)
1711 Lisp_Object tail;
1712 bool first_string = 1;
1713 Lisp_Object error_message;
1715 error_message = Qnil;
1716 for (tail = Vdebug_ignored_errors; CONSP (tail); tail = XCDR (tail))
1718 if (STRINGP (XCAR (tail)))
1720 if (first_string)
1722 error_message = Ferror_message_string (data);
1723 first_string = 0;
1726 if (fast_string_match (XCAR (tail), error_message) >= 0)
1727 return 1;
1729 else
1731 Lisp_Object contail;
1733 for (contail = conditions; CONSP (contail); contail = XCDR (contail))
1734 if (EQ (XCAR (tail), XCAR (contail)))
1735 return 1;
1739 return 0;
1742 /* Call the debugger if calling it is currently enabled for CONDITIONS.
1743 SIG and DATA describe the signal. There are two ways to pass them:
1744 = SIG is the error symbol, and DATA is the rest of the data.
1745 = SIG is nil, and DATA is (SYMBOL . REST-OF-DATA).
1746 This is for memory-full errors only. */
1747 static bool
1748 maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig, Lisp_Object data)
1750 Lisp_Object combined_data;
1752 combined_data = Fcons (sig, data);
1754 if (
1755 /* Don't try to run the debugger with interrupts blocked.
1756 The editing loop would return anyway. */
1757 ! input_blocked_p ()
1758 && NILP (Vinhibit_debugger)
1759 /* Does user want to enter debugger for this kind of error? */
1760 && (EQ (sig, Qquit)
1761 ? debug_on_quit
1762 : wants_debugger (Vdebug_on_error, conditions))
1763 && ! skip_debugger (conditions, combined_data)
1764 /* RMS: What's this for? */
1765 && when_entered_debugger < num_nonmacro_input_events)
1767 call_debugger (list2 (Qerror, combined_data));
1768 return 1;
1771 return 0;
1774 static Lisp_Object
1775 find_handler_clause (Lisp_Object handlers, Lisp_Object conditions)
1777 register Lisp_Object h;
1779 /* t is used by handlers for all conditions, set up by C code. */
1780 if (EQ (handlers, Qt))
1781 return Qt;
1783 /* error is used similarly, but means print an error message
1784 and run the debugger if that is enabled. */
1785 if (EQ (handlers, Qerror))
1786 return Qt;
1788 for (h = handlers; CONSP (h); h = XCDR (h))
1790 Lisp_Object handler = XCAR (h);
1791 if (!NILP (Fmemq (handler, conditions)))
1792 return handlers;
1795 return Qnil;
1799 /* Format and return a string; called like vprintf. */
1800 Lisp_Object
1801 vformat_string (const char *m, va_list ap)
1803 char buf[4000];
1804 ptrdiff_t size = sizeof buf;
1805 ptrdiff_t size_max = STRING_BYTES_BOUND + 1;
1806 char *buffer = buf;
1807 ptrdiff_t used;
1808 Lisp_Object string;
1810 used = evxprintf (&buffer, &size, buf, size_max, m, ap);
1811 string = make_string (buffer, used);
1812 if (buffer != buf)
1813 xfree (buffer);
1815 return string;
1818 /* Dump an error message; called like vprintf. */
1819 void
1820 verror (const char *m, va_list ap)
1822 xsignal1 (Qerror, vformat_string (m, ap));
1826 /* Dump an error message; called like printf. */
1828 /* VARARGS 1 */
1829 void
1830 error (const char *m, ...)
1832 va_list ap;
1833 va_start (ap, m);
1834 verror (m, ap);
1837 DEFUN ("commandp", Fcommandp, Scommandp, 1, 2, 0,
1838 doc: /* Non-nil if FUNCTION makes provisions for interactive calling.
1839 This means it contains a description for how to read arguments to give it.
1840 The value is nil for an invalid function or a symbol with no function
1841 definition.
1843 Interactively callable functions include strings and vectors (treated
1844 as keyboard macros), lambda-expressions that contain a top-level call
1845 to `interactive', autoload definitions made by `autoload' with non-nil
1846 fourth argument, and some of the built-in functions of Lisp.
1848 Also, a symbol satisfies `commandp' if its function definition does so.
1850 If the optional argument FOR-CALL-INTERACTIVELY is non-nil,
1851 then strings and vectors are not accepted. */)
1852 (Lisp_Object function, Lisp_Object for_call_interactively)
1854 register Lisp_Object fun;
1855 register Lisp_Object funcar;
1856 Lisp_Object if_prop = Qnil;
1858 fun = function;
1860 fun = indirect_function (fun); /* Check cycles. */
1861 if (NILP (fun))
1862 return Qnil;
1864 /* Check an `interactive-form' property if present, analogous to the
1865 function-documentation property. */
1866 fun = function;
1867 while (SYMBOLP (fun))
1869 Lisp_Object tmp = Fget (fun, Qinteractive_form);
1870 if (!NILP (tmp))
1871 if_prop = Qt;
1872 fun = Fsymbol_function (fun);
1875 /* Emacs primitives are interactive if their DEFUN specifies an
1876 interactive spec. */
1877 if (SUBRP (fun))
1878 return XSUBR (fun)->intspec ? Qt : if_prop;
1880 /* Bytecode objects are interactive if they are long enough to
1881 have an element whose index is COMPILED_INTERACTIVE, which is
1882 where the interactive spec is stored. */
1883 else if (COMPILEDP (fun))
1884 return ((ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK) > COMPILED_INTERACTIVE
1885 ? Qt : if_prop);
1887 /* Strings and vectors are keyboard macros. */
1888 if (STRINGP (fun) || VECTORP (fun))
1889 return (NILP (for_call_interactively) ? Qt : Qnil);
1891 /* Lists may represent commands. */
1892 if (!CONSP (fun))
1893 return Qnil;
1894 funcar = XCAR (fun);
1895 if (EQ (funcar, Qclosure))
1896 return (!NILP (Fassq (Qinteractive, Fcdr (Fcdr (XCDR (fun)))))
1897 ? Qt : if_prop);
1898 else if (EQ (funcar, Qlambda))
1899 return !NILP (Fassq (Qinteractive, Fcdr (XCDR (fun)))) ? Qt : if_prop;
1900 else if (EQ (funcar, Qautoload))
1901 return !NILP (Fcar (Fcdr (Fcdr (XCDR (fun))))) ? Qt : if_prop;
1902 else
1903 return Qnil;
1906 DEFUN ("autoload", Fautoload, Sautoload, 2, 5, 0,
1907 doc: /* Define FUNCTION to autoload from FILE.
1908 FUNCTION is a symbol; FILE is a file name string to pass to `load'.
1909 Third arg DOCSTRING is documentation for the function.
1910 Fourth arg INTERACTIVE if non-nil says function can be called interactively.
1911 Fifth arg TYPE indicates the type of the object:
1912 nil or omitted says FUNCTION is a function,
1913 `keymap' says FUNCTION is really a keymap, and
1914 `macro' or t says FUNCTION is really a macro.
1915 Third through fifth args give info about the real definition.
1916 They default to nil.
1917 If FUNCTION is already defined other than as an autoload,
1918 this does nothing and returns nil. */)
1919 (Lisp_Object function, Lisp_Object file, Lisp_Object docstring, Lisp_Object interactive, Lisp_Object type)
1921 CHECK_SYMBOL (function);
1922 CHECK_STRING (file);
1924 /* If function is defined and not as an autoload, don't override. */
1925 if (!NILP (XSYMBOL (function)->function)
1926 && !AUTOLOADP (XSYMBOL (function)->function))
1927 return Qnil;
1929 if (!NILP (Vpurify_flag) && EQ (docstring, make_number (0)))
1930 /* `read1' in lread.c has found the docstring starting with "\
1931 and assumed the docstring will be provided by Snarf-documentation, so it
1932 passed us 0 instead. But that leads to accidental sharing in purecopy's
1933 hash-consing, so we use a (hopefully) unique integer instead. */
1934 docstring = make_number (XHASH (function));
1935 return Fdefalias (function,
1936 list5 (Qautoload, file, docstring, interactive, type),
1937 Qnil);
1940 void
1941 un_autoload (Lisp_Object oldqueue)
1943 Lisp_Object queue, first, second;
1945 /* Queue to unwind is current value of Vautoload_queue.
1946 oldqueue is the shadowed value to leave in Vautoload_queue. */
1947 queue = Vautoload_queue;
1948 Vautoload_queue = oldqueue;
1949 while (CONSP (queue))
1951 first = XCAR (queue);
1952 second = Fcdr (first);
1953 first = Fcar (first);
1954 if (EQ (first, make_number (0)))
1955 Vfeatures = second;
1956 else
1957 Ffset (first, second);
1958 queue = XCDR (queue);
1962 /* Load an autoloaded function.
1963 FUNNAME is the symbol which is the function's name.
1964 FUNDEF is the autoload definition (a list). */
1966 DEFUN ("autoload-do-load", Fautoload_do_load, Sautoload_do_load, 1, 3, 0,
1967 doc: /* Load FUNDEF which should be an autoload.
1968 If non-nil, FUNNAME should be the symbol whose function value is FUNDEF,
1969 in which case the function returns the new autoloaded function value.
1970 If equal to `macro', MACRO-ONLY specifies that FUNDEF should only be loaded if
1971 it defines a macro. */)
1972 (Lisp_Object fundef, Lisp_Object funname, Lisp_Object macro_only)
1974 ptrdiff_t count = SPECPDL_INDEX ();
1976 if (!CONSP (fundef) || !EQ (Qautoload, XCAR (fundef)))
1977 return fundef;
1979 /* In the special case that we are generating ldefs-boot-auto.el,
1980 then be noisy about the autoload. */
1981 if( generating_ldefs_boot )
1983 fprintf(stderr, "(autoload '");
1984 Fprin1(funname,Qexternal_debugging_output);
1985 fprintf(stderr, " ");
1986 Fprin1(Fcar (Fcdr (fundef)),Qexternal_debugging_output);
1987 fprintf(stderr, " nil nil ");
1989 Lisp_Object kind = Fnth (make_number (4), fundef);
1990 if (! (EQ (kind, Qt) || EQ (kind, Qmacro)))
1992 fprintf(stderr, "nil");
1994 else
1996 fprintf(stderr, "t");
1998 fprintf(stderr, ")\n");
2001 if (EQ (macro_only, Qmacro))
2003 Lisp_Object kind = Fnth (make_number (4), fundef);
2004 if (! (EQ (kind, Qt) || EQ (kind, Qmacro)))
2005 return fundef;
2008 /* This is to make sure that loadup.el gives a clear picture
2009 of what files are preloaded and when. */
2010 if (! NILP (Vpurify_flag))
2011 error ("Attempt to autoload %s while preparing to dump",
2012 SDATA (SYMBOL_NAME (funname)));
2014 CHECK_SYMBOL (funname);
2016 /* Preserve the match data. */
2017 record_unwind_save_match_data ();
2019 /* If autoloading gets an error (which includes the error of failing
2020 to define the function being called), we use Vautoload_queue
2021 to undo function definitions and `provide' calls made by
2022 the function. We do this in the specific case of autoloading
2023 because autoloading is not an explicit request "load this file",
2024 but rather a request to "call this function".
2026 The value saved here is to be restored into Vautoload_queue. */
2027 record_unwind_protect (un_autoload, Vautoload_queue);
2028 Vautoload_queue = Qt;
2029 /* If `macro_only', assume this autoload to be a "best-effort",
2030 so don't signal an error if autoloading fails. */
2031 Fload (Fcar (Fcdr (fundef)), macro_only, Qt, Qnil, Qt);
2033 /* Once loading finishes, don't undo it. */
2034 Vautoload_queue = Qt;
2035 unbind_to (count, Qnil);
2037 if (NILP (funname))
2038 return Qnil;
2039 else
2041 Lisp_Object fun = Findirect_function (funname, Qnil);
2043 if (!NILP (Fequal (fun, fundef)))
2044 error ("Autoloading file %s failed to define function %s",
2045 SDATA (Fcar (Fcar (Vload_history))),
2046 SDATA (SYMBOL_NAME (funname)));
2047 else
2048 return fun;
2053 DEFUN ("eval", Feval, Seval, 1, 2, 0,
2054 doc: /* Evaluate FORM and return its value.
2055 If LEXICAL is t, evaluate using lexical scoping.
2056 LEXICAL can also be an actual lexical environment, in the form of an
2057 alist mapping symbols to their value. */)
2058 (Lisp_Object form, Lisp_Object lexical)
2060 ptrdiff_t count = SPECPDL_INDEX ();
2061 specbind (Qinternal_interpreter_environment,
2062 CONSP (lexical) || NILP (lexical) ? lexical : list1 (Qt));
2063 return unbind_to (count, eval_sub (form));
2066 /* Grow the specpdl stack by one entry.
2067 The caller should have already initialized the entry.
2068 Signal an error on stack overflow.
2070 Make sure that there is always one unused entry past the top of the
2071 stack, so that the just-initialized entry is safely unwound if
2072 memory exhausted and an error is signaled here. Also, allocate a
2073 never-used entry just before the bottom of the stack; sometimes its
2074 address is taken. */
2076 static void
2077 grow_specpdl (void)
2079 specpdl_ptr++;
2081 if (specpdl_ptr == specpdl + specpdl_size)
2083 ptrdiff_t count = SPECPDL_INDEX ();
2084 ptrdiff_t max_size = min (max_specpdl_size, PTRDIFF_MAX - 1000);
2085 union specbinding *pdlvec = specpdl - 1;
2086 ptrdiff_t pdlvecsize = specpdl_size + 1;
2087 if (max_size <= specpdl_size)
2089 if (max_specpdl_size < 400)
2090 max_size = max_specpdl_size = 400;
2091 if (max_size <= specpdl_size)
2092 signal_error ("Variable binding depth exceeds max-specpdl-size",
2093 Qnil);
2095 pdlvec = xpalloc (pdlvec, &pdlvecsize, 1, max_size + 1, sizeof *specpdl);
2096 specpdl = pdlvec + 1;
2097 specpdl_size = pdlvecsize - 1;
2098 specpdl_ptr = specpdl + count;
2102 ptrdiff_t
2103 record_in_backtrace (Lisp_Object function, Lisp_Object *args, ptrdiff_t nargs)
2105 ptrdiff_t count = SPECPDL_INDEX ();
2107 eassert (nargs >= UNEVALLED);
2108 specpdl_ptr->bt.kind = SPECPDL_BACKTRACE;
2109 specpdl_ptr->bt.debug_on_exit = false;
2110 specpdl_ptr->bt.function = function;
2111 specpdl_ptr->bt.args = args;
2112 specpdl_ptr->bt.nargs = nargs;
2113 grow_specpdl ();
2115 return count;
2118 /* Eval a sub-expression of the current expression (i.e. in the same
2119 lexical scope). */
2120 Lisp_Object
2121 eval_sub (Lisp_Object form)
2123 Lisp_Object fun, val, original_fun, original_args;
2124 Lisp_Object funcar;
2125 ptrdiff_t count;
2127 /* Declare here, as this array may be accessed by call_debugger near
2128 the end of this function. See Bug#21245. */
2129 Lisp_Object argvals[8];
2131 if (SYMBOLP (form))
2133 /* Look up its binding in the lexical environment.
2134 We do not pay attention to the declared_special flag here, since we
2135 already did that when let-binding the variable. */
2136 Lisp_Object lex_binding
2137 = !NILP (Vinternal_interpreter_environment) /* Mere optimization! */
2138 ? Fassq (form, Vinternal_interpreter_environment)
2139 : Qnil;
2140 if (CONSP (lex_binding))
2141 return XCDR (lex_binding);
2142 else
2143 return Fsymbol_value (form);
2146 if (!CONSP (form))
2147 return form;
2149 maybe_quit ();
2151 maybe_gc ();
2153 if (++lisp_eval_depth > max_lisp_eval_depth)
2155 if (max_lisp_eval_depth < 100)
2156 max_lisp_eval_depth = 100;
2157 if (lisp_eval_depth > max_lisp_eval_depth)
2158 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2161 original_fun = XCAR (form);
2162 original_args = XCDR (form);
2164 /* This also protects them from gc. */
2165 count = record_in_backtrace (original_fun, &original_args, UNEVALLED);
2167 if (debug_on_next_call)
2168 do_debug_on_call (Qt, count);
2170 /* At this point, only original_fun and original_args
2171 have values that will be used below. */
2172 retry:
2174 /* Optimize for no indirection. */
2175 fun = original_fun;
2176 if (!SYMBOLP (fun))
2177 fun = Ffunction (Fcons (fun, Qnil));
2178 else if (!NILP (fun) && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2179 fun = indirect_function (fun);
2181 if (SUBRP (fun))
2183 Lisp_Object args_left = original_args;
2184 Lisp_Object numargs = Flength (args_left);
2186 check_cons_list ();
2188 if (XINT (numargs) < XSUBR (fun)->min_args
2189 || (XSUBR (fun)->max_args >= 0
2190 && XSUBR (fun)->max_args < XINT (numargs)))
2191 xsignal2 (Qwrong_number_of_arguments, original_fun, numargs);
2193 else if (XSUBR (fun)->max_args == UNEVALLED)
2194 val = (XSUBR (fun)->function.aUNEVALLED) (args_left);
2195 else if (XSUBR (fun)->max_args == MANY)
2197 /* Pass a vector of evaluated arguments. */
2198 Lisp_Object *vals;
2199 ptrdiff_t argnum = 0;
2200 USE_SAFE_ALLOCA;
2202 SAFE_ALLOCA_LISP (vals, XINT (numargs));
2204 while (!NILP (args_left))
2206 vals[argnum++] = eval_sub (Fcar (args_left));
2207 args_left = Fcdr (args_left);
2210 set_backtrace_args (specpdl + count, vals, XINT (numargs));
2212 val = (XSUBR (fun)->function.aMANY) (XINT (numargs), vals);
2214 check_cons_list ();
2215 lisp_eval_depth--;
2216 /* Do the debug-on-exit now, while VALS still exists. */
2217 if (backtrace_debug_on_exit (specpdl + count))
2218 val = call_debugger (list2 (Qexit, val));
2219 SAFE_FREE ();
2220 specpdl_ptr--;
2221 return val;
2223 else
2225 int i, maxargs = XSUBR (fun)->max_args;
2227 for (i = 0; i < maxargs; i++)
2229 argvals[i] = eval_sub (Fcar (args_left));
2230 args_left = Fcdr (args_left);
2233 set_backtrace_args (specpdl + count, argvals, XINT (numargs));
2235 switch (i)
2237 case 0:
2238 val = (XSUBR (fun)->function.a0 ());
2239 break;
2240 case 1:
2241 val = (XSUBR (fun)->function.a1 (argvals[0]));
2242 break;
2243 case 2:
2244 val = (XSUBR (fun)->function.a2 (argvals[0], argvals[1]));
2245 break;
2246 case 3:
2247 val = (XSUBR (fun)->function.a3
2248 (argvals[0], argvals[1], argvals[2]));
2249 break;
2250 case 4:
2251 val = (XSUBR (fun)->function.a4
2252 (argvals[0], argvals[1], argvals[2], argvals[3]));
2253 break;
2254 case 5:
2255 val = (XSUBR (fun)->function.a5
2256 (argvals[0], argvals[1], argvals[2], argvals[3],
2257 argvals[4]));
2258 break;
2259 case 6:
2260 val = (XSUBR (fun)->function.a6
2261 (argvals[0], argvals[1], argvals[2], argvals[3],
2262 argvals[4], argvals[5]));
2263 break;
2264 case 7:
2265 val = (XSUBR (fun)->function.a7
2266 (argvals[0], argvals[1], argvals[2], argvals[3],
2267 argvals[4], argvals[5], argvals[6]));
2268 break;
2270 case 8:
2271 val = (XSUBR (fun)->function.a8
2272 (argvals[0], argvals[1], argvals[2], argvals[3],
2273 argvals[4], argvals[5], argvals[6], argvals[7]));
2274 break;
2276 default:
2277 /* Someone has created a subr that takes more arguments than
2278 is supported by this code. We need to either rewrite the
2279 subr to use a different argument protocol, or add more
2280 cases to this switch. */
2281 emacs_abort ();
2285 else if (COMPILEDP (fun))
2286 return apply_lambda (fun, original_args, count);
2287 else
2289 if (NILP (fun))
2290 xsignal1 (Qvoid_function, original_fun);
2291 if (!CONSP (fun))
2292 xsignal1 (Qinvalid_function, original_fun);
2293 funcar = XCAR (fun);
2294 if (!SYMBOLP (funcar))
2295 xsignal1 (Qinvalid_function, original_fun);
2296 if (EQ (funcar, Qautoload))
2298 Fautoload_do_load (fun, original_fun, Qnil);
2299 goto retry;
2301 if (EQ (funcar, Qmacro))
2303 ptrdiff_t count1 = SPECPDL_INDEX ();
2304 Lisp_Object exp;
2305 /* Bind lexical-binding during expansion of the macro, so the
2306 macro can know reliably if the code it outputs will be
2307 interpreted using lexical-binding or not. */
2308 specbind (Qlexical_binding,
2309 NILP (Vinternal_interpreter_environment) ? Qnil : Qt);
2310 exp = apply1 (Fcdr (fun), original_args);
2311 unbind_to (count1, Qnil);
2312 val = eval_sub (exp);
2314 else if (EQ (funcar, Qlambda)
2315 || EQ (funcar, Qclosure))
2316 return apply_lambda (fun, original_args, count);
2317 else
2318 xsignal1 (Qinvalid_function, original_fun);
2320 check_cons_list ();
2322 lisp_eval_depth--;
2323 if (backtrace_debug_on_exit (specpdl + count))
2324 val = call_debugger (list2 (Qexit, val));
2325 specpdl_ptr--;
2327 return val;
2330 DEFUN ("apply", Fapply, Sapply, 1, MANY, 0,
2331 doc: /* Call FUNCTION with our remaining args, using our last arg as list of args.
2332 Then return the value FUNCTION returns.
2333 Thus, (apply \\='+ 1 2 \\='(3 4)) returns 10.
2334 usage: (apply FUNCTION &rest ARGUMENTS) */)
2335 (ptrdiff_t nargs, Lisp_Object *args)
2337 ptrdiff_t i, numargs, funcall_nargs;
2338 register Lisp_Object *funcall_args = NULL;
2339 register Lisp_Object spread_arg = args[nargs - 1];
2340 Lisp_Object fun = args[0];
2341 Lisp_Object retval;
2342 USE_SAFE_ALLOCA;
2344 CHECK_LIST (spread_arg);
2346 numargs = XINT (Flength (spread_arg));
2348 if (numargs == 0)
2349 return Ffuncall (nargs - 1, args);
2350 else if (numargs == 1)
2352 args [nargs - 1] = XCAR (spread_arg);
2353 return Ffuncall (nargs, args);
2356 numargs += nargs - 2;
2358 /* Optimize for no indirection. */
2359 if (SYMBOLP (fun) && !NILP (fun)
2360 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2362 fun = indirect_function (fun);
2363 if (NILP (fun))
2364 /* Let funcall get the error. */
2365 fun = args[0];
2368 if (SUBRP (fun) && XSUBR (fun)->max_args > numargs
2369 /* Don't hide an error by adding missing arguments. */
2370 && numargs >= XSUBR (fun)->min_args)
2372 /* Avoid making funcall cons up a yet another new vector of arguments
2373 by explicitly supplying nil's for optional values. */
2374 SAFE_ALLOCA_LISP (funcall_args, 1 + XSUBR (fun)->max_args);
2375 memclear (funcall_args + numargs + 1,
2376 (XSUBR (fun)->max_args - numargs) * word_size);
2377 funcall_nargs = 1 + XSUBR (fun)->max_args;
2379 else
2380 { /* We add 1 to numargs because funcall_args includes the
2381 function itself as well as its arguments. */
2382 SAFE_ALLOCA_LISP (funcall_args, 1 + numargs);
2383 funcall_nargs = 1 + numargs;
2386 memcpy (funcall_args, args, nargs * word_size);
2387 /* Spread the last arg we got. Its first element goes in
2388 the slot that it used to occupy, hence this value of I. */
2389 i = nargs - 1;
2390 while (!NILP (spread_arg))
2392 funcall_args [i++] = XCAR (spread_arg);
2393 spread_arg = XCDR (spread_arg);
2396 retval = Ffuncall (funcall_nargs, funcall_args);
2398 SAFE_FREE ();
2399 return retval;
2402 /* Run hook variables in various ways. */
2404 static Lisp_Object
2405 funcall_nil (ptrdiff_t nargs, Lisp_Object *args)
2407 Ffuncall (nargs, args);
2408 return Qnil;
2411 DEFUN ("run-hooks", Frun_hooks, Srun_hooks, 0, MANY, 0,
2412 doc: /* Run each hook in HOOKS.
2413 Each argument should be a symbol, a hook variable.
2414 These symbols are processed in the order specified.
2415 If a hook symbol has a non-nil value, that value may be a function
2416 or a list of functions to be called to run the hook.
2417 If the value is a function, it is called with no arguments.
2418 If it is a list, the elements are called, in order, with no arguments.
2420 Major modes should not use this function directly to run their mode
2421 hook; they should use `run-mode-hooks' instead.
2423 Do not use `make-local-variable' to make a hook variable buffer-local.
2424 Instead, use `add-hook' and specify t for the LOCAL argument.
2425 usage: (run-hooks &rest HOOKS) */)
2426 (ptrdiff_t nargs, Lisp_Object *args)
2428 ptrdiff_t i;
2430 for (i = 0; i < nargs; i++)
2431 run_hook (args[i]);
2433 return Qnil;
2436 DEFUN ("run-hook-with-args", Frun_hook_with_args,
2437 Srun_hook_with_args, 1, MANY, 0,
2438 doc: /* Run HOOK with the specified arguments ARGS.
2439 HOOK should be a symbol, a hook variable. The value of HOOK
2440 may be nil, a function, or a list of functions. Call each
2441 function in order with arguments ARGS. The final return value
2442 is unspecified.
2444 Do not use `make-local-variable' to make a hook variable buffer-local.
2445 Instead, use `add-hook' and specify t for the LOCAL argument.
2446 usage: (run-hook-with-args HOOK &rest ARGS) */)
2447 (ptrdiff_t nargs, Lisp_Object *args)
2449 return run_hook_with_args (nargs, args, funcall_nil);
2452 /* NB this one still documents a specific non-nil return value.
2453 (As did run-hook-with-args and run-hook-with-args-until-failure
2454 until they were changed in 24.1.) */
2455 DEFUN ("run-hook-with-args-until-success", Frun_hook_with_args_until_success,
2456 Srun_hook_with_args_until_success, 1, MANY, 0,
2457 doc: /* Run HOOK with the specified arguments ARGS.
2458 HOOK should be a symbol, a hook variable. The value of HOOK
2459 may be nil, a function, or a list of functions. Call each
2460 function in order with arguments ARGS, stopping at the first
2461 one that returns non-nil, and return that value. Otherwise (if
2462 all functions return nil, or if there are no functions to call),
2463 return nil.
2465 Do not use `make-local-variable' to make a hook variable buffer-local.
2466 Instead, use `add-hook' and specify t for the LOCAL argument.
2467 usage: (run-hook-with-args-until-success HOOK &rest ARGS) */)
2468 (ptrdiff_t nargs, Lisp_Object *args)
2470 return run_hook_with_args (nargs, args, Ffuncall);
2473 static Lisp_Object
2474 funcall_not (ptrdiff_t nargs, Lisp_Object *args)
2476 return NILP (Ffuncall (nargs, args)) ? Qt : Qnil;
2479 DEFUN ("run-hook-with-args-until-failure", Frun_hook_with_args_until_failure,
2480 Srun_hook_with_args_until_failure, 1, MANY, 0,
2481 doc: /* Run HOOK with the specified arguments ARGS.
2482 HOOK should be a symbol, a hook variable. The value of HOOK
2483 may be nil, a function, or a list of functions. Call each
2484 function in order with arguments ARGS, stopping at the first
2485 one that returns nil, and return nil. Otherwise (if all functions
2486 return non-nil, or if there are no functions to call), return non-nil
2487 \(do not rely on the precise return value in this case).
2489 Do not use `make-local-variable' to make a hook variable buffer-local.
2490 Instead, use `add-hook' and specify t for the LOCAL argument.
2491 usage: (run-hook-with-args-until-failure HOOK &rest ARGS) */)
2492 (ptrdiff_t nargs, Lisp_Object *args)
2494 return NILP (run_hook_with_args (nargs, args, funcall_not)) ? Qt : Qnil;
2497 static Lisp_Object
2498 run_hook_wrapped_funcall (ptrdiff_t nargs, Lisp_Object *args)
2500 Lisp_Object tmp = args[0], ret;
2501 args[0] = args[1];
2502 args[1] = tmp;
2503 ret = Ffuncall (nargs, args);
2504 args[1] = args[0];
2505 args[0] = tmp;
2506 return ret;
2509 DEFUN ("run-hook-wrapped", Frun_hook_wrapped, Srun_hook_wrapped, 2, MANY, 0,
2510 doc: /* Run HOOK, passing each function through WRAP-FUNCTION.
2511 I.e. instead of calling each function FUN directly with arguments ARGS,
2512 it calls WRAP-FUNCTION with arguments FUN and ARGS.
2513 As soon as a call to WRAP-FUNCTION returns non-nil, `run-hook-wrapped'
2514 aborts and returns that value.
2515 usage: (run-hook-wrapped HOOK WRAP-FUNCTION &rest ARGS) */)
2516 (ptrdiff_t nargs, Lisp_Object *args)
2518 return run_hook_with_args (nargs, args, run_hook_wrapped_funcall);
2521 /* ARGS[0] should be a hook symbol.
2522 Call each of the functions in the hook value, passing each of them
2523 as arguments all the rest of ARGS (all NARGS - 1 elements).
2524 FUNCALL specifies how to call each function on the hook. */
2526 Lisp_Object
2527 run_hook_with_args (ptrdiff_t nargs, Lisp_Object *args,
2528 Lisp_Object (*funcall) (ptrdiff_t nargs, Lisp_Object *args))
2530 Lisp_Object sym, val, ret = Qnil;
2532 /* If we are dying or still initializing,
2533 don't do anything--it would probably crash if we tried. */
2534 if (NILP (Vrun_hooks))
2535 return Qnil;
2537 sym = args[0];
2538 val = find_symbol_value (sym);
2540 if (EQ (val, Qunbound) || NILP (val))
2541 return ret;
2542 else if (!CONSP (val) || FUNCTIONP (val))
2544 args[0] = val;
2545 return funcall (nargs, args);
2547 else
2549 Lisp_Object global_vals = Qnil;
2551 for (;
2552 CONSP (val) && NILP (ret);
2553 val = XCDR (val))
2555 if (EQ (XCAR (val), Qt))
2557 /* t indicates this hook has a local binding;
2558 it means to run the global binding too. */
2559 global_vals = Fdefault_value (sym);
2560 if (NILP (global_vals)) continue;
2562 if (!CONSP (global_vals) || EQ (XCAR (global_vals), Qlambda))
2564 args[0] = global_vals;
2565 ret = funcall (nargs, args);
2567 else
2569 for (;
2570 CONSP (global_vals) && NILP (ret);
2571 global_vals = XCDR (global_vals))
2573 args[0] = XCAR (global_vals);
2574 /* In a global value, t should not occur. If it does, we
2575 must ignore it to avoid an endless loop. */
2576 if (!EQ (args[0], Qt))
2577 ret = funcall (nargs, args);
2581 else
2583 args[0] = XCAR (val);
2584 ret = funcall (nargs, args);
2588 return ret;
2592 /* Run the hook HOOK, giving each function no args. */
2594 void
2595 run_hook (Lisp_Object hook)
2597 Frun_hook_with_args (1, &hook);
2600 /* Run the hook HOOK, giving each function the two args ARG1 and ARG2. */
2602 void
2603 run_hook_with_args_2 (Lisp_Object hook, Lisp_Object arg1, Lisp_Object arg2)
2605 CALLN (Frun_hook_with_args, hook, arg1, arg2);
2608 /* Apply fn to arg. */
2609 Lisp_Object
2610 apply1 (Lisp_Object fn, Lisp_Object arg)
2612 return NILP (arg) ? Ffuncall (1, &fn) : CALLN (Fapply, fn, arg);
2615 /* Call function fn on no arguments. */
2616 Lisp_Object
2617 call0 (Lisp_Object fn)
2619 return Ffuncall (1, &fn);
2622 /* Call function fn with 1 argument arg1. */
2623 /* ARGSUSED */
2624 Lisp_Object
2625 call1 (Lisp_Object fn, Lisp_Object arg1)
2627 return CALLN (Ffuncall, fn, arg1);
2630 /* Call function fn with 2 arguments arg1, arg2. */
2631 /* ARGSUSED */
2632 Lisp_Object
2633 call2 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2)
2635 return CALLN (Ffuncall, fn, arg1, arg2);
2638 /* Call function fn with 3 arguments arg1, arg2, arg3. */
2639 /* ARGSUSED */
2640 Lisp_Object
2641 call3 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2643 return CALLN (Ffuncall, fn, arg1, arg2, arg3);
2646 /* Call function fn with 4 arguments arg1, arg2, arg3, arg4. */
2647 /* ARGSUSED */
2648 Lisp_Object
2649 call4 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2650 Lisp_Object arg4)
2652 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4);
2655 /* Call function fn with 5 arguments arg1, arg2, arg3, arg4, arg5. */
2656 /* ARGSUSED */
2657 Lisp_Object
2658 call5 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2659 Lisp_Object arg4, Lisp_Object arg5)
2661 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5);
2664 /* Call function fn with 6 arguments arg1, arg2, arg3, arg4, arg5, arg6. */
2665 /* ARGSUSED */
2666 Lisp_Object
2667 call6 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2668 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6)
2670 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6);
2673 /* Call function fn with 7 arguments arg1, arg2, arg3, arg4, arg5, arg6, arg7. */
2674 /* ARGSUSED */
2675 Lisp_Object
2676 call7 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2677 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6, Lisp_Object arg7)
2679 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
2682 DEFUN ("functionp", Ffunctionp, Sfunctionp, 1, 1, 0,
2683 doc: /* Non-nil if OBJECT is a function. */)
2684 (Lisp_Object object)
2686 if (FUNCTIONP (object))
2687 return Qt;
2688 return Qnil;
2691 bool
2692 FUNCTIONP (Lisp_Object object)
2694 if (SYMBOLP (object) && !NILP (Ffboundp (object)))
2696 object = Findirect_function (object, Qt);
2698 if (CONSP (object) && EQ (XCAR (object), Qautoload))
2700 /* Autoloaded symbols are functions, except if they load
2701 macros or keymaps. */
2702 for (int i = 0; i < 4 && CONSP (object); i++)
2703 object = XCDR (object);
2705 return ! (CONSP (object) && !NILP (XCAR (object)));
2709 if (SUBRP (object))
2710 return XSUBR (object)->max_args != UNEVALLED;
2711 else if (COMPILEDP (object))
2712 return true;
2713 else if (CONSP (object))
2715 Lisp_Object car = XCAR (object);
2716 return EQ (car, Qlambda) || EQ (car, Qclosure);
2718 else
2719 return false;
2722 DEFUN ("funcall", Ffuncall, Sfuncall, 1, MANY, 0,
2723 doc: /* Call first argument as a function, passing remaining arguments to it.
2724 Return the value that function returns.
2725 Thus, (funcall \\='cons \\='x \\='y) returns (x . y).
2726 usage: (funcall FUNCTION &rest ARGUMENTS) */)
2727 (ptrdiff_t nargs, Lisp_Object *args)
2729 Lisp_Object fun, original_fun;
2730 Lisp_Object funcar;
2731 ptrdiff_t numargs = nargs - 1;
2732 Lisp_Object val;
2733 ptrdiff_t count;
2735 maybe_quit ();
2737 if (++lisp_eval_depth > max_lisp_eval_depth)
2739 if (max_lisp_eval_depth < 100)
2740 max_lisp_eval_depth = 100;
2741 if (lisp_eval_depth > max_lisp_eval_depth)
2742 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2745 count = record_in_backtrace (args[0], &args[1], nargs - 1);
2747 maybe_gc ();
2749 if (debug_on_next_call)
2750 do_debug_on_call (Qlambda, count);
2752 check_cons_list ();
2754 original_fun = args[0];
2756 retry:
2758 /* Optimize for no indirection. */
2759 fun = original_fun;
2760 if (SYMBOLP (fun) && !NILP (fun)
2761 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2762 fun = indirect_function (fun);
2764 if (SUBRP (fun))
2765 val = funcall_subr (XSUBR (fun), numargs, args + 1);
2766 else if (COMPILEDP (fun))
2767 val = funcall_lambda (fun, numargs, args + 1);
2768 else
2770 if (NILP (fun))
2771 xsignal1 (Qvoid_function, original_fun);
2772 if (!CONSP (fun))
2773 xsignal1 (Qinvalid_function, original_fun);
2774 funcar = XCAR (fun);
2775 if (!SYMBOLP (funcar))
2776 xsignal1 (Qinvalid_function, original_fun);
2777 if (EQ (funcar, Qlambda)
2778 || EQ (funcar, Qclosure))
2779 val = funcall_lambda (fun, numargs, args + 1);
2780 else if (EQ (funcar, Qautoload))
2782 Fautoload_do_load (fun, original_fun, Qnil);
2783 check_cons_list ();
2784 goto retry;
2786 else
2787 xsignal1 (Qinvalid_function, original_fun);
2789 check_cons_list ();
2790 lisp_eval_depth--;
2791 if (backtrace_debug_on_exit (specpdl + count))
2792 val = call_debugger (list2 (Qexit, val));
2793 specpdl_ptr--;
2794 return val;
2798 /* Apply a C subroutine SUBR to the NUMARGS evaluated arguments in ARG_VECTOR
2799 and return the result of evaluation. */
2801 Lisp_Object
2802 funcall_subr (struct Lisp_Subr *subr, ptrdiff_t numargs, Lisp_Object *args)
2804 if (numargs < subr->min_args
2805 || (subr->max_args >= 0 && subr->max_args < numargs))
2807 Lisp_Object fun;
2808 XSETSUBR (fun, subr);
2809 xsignal2 (Qwrong_number_of_arguments, fun, make_number (numargs));
2812 else if (subr->max_args == UNEVALLED)
2814 Lisp_Object fun;
2815 XSETSUBR (fun, subr);
2816 xsignal1 (Qinvalid_function, fun);
2819 else if (subr->max_args == MANY)
2820 return (subr->function.aMANY) (numargs, args);
2821 else
2823 Lisp_Object internal_argbuf[8];
2824 Lisp_Object *internal_args;
2825 if (subr->max_args > numargs)
2827 eassert (subr->max_args <= ARRAYELTS (internal_argbuf));
2828 internal_args = internal_argbuf;
2829 memcpy (internal_args, args, numargs * word_size);
2830 memclear (internal_args + numargs,
2831 (subr->max_args - numargs) * word_size);
2833 else
2834 internal_args = args;
2835 switch (subr->max_args)
2837 case 0:
2838 return (subr->function.a0 ());
2839 case 1:
2840 return (subr->function.a1 (internal_args[0]));
2841 case 2:
2842 return (subr->function.a2
2843 (internal_args[0], internal_args[1]));
2844 case 3:
2845 return (subr->function.a3
2846 (internal_args[0], internal_args[1], internal_args[2]));
2847 case 4:
2848 return (subr->function.a4
2849 (internal_args[0], internal_args[1], internal_args[2],
2850 internal_args[3]));
2851 case 5:
2852 return (subr->function.a5
2853 (internal_args[0], internal_args[1], internal_args[2],
2854 internal_args[3], internal_args[4]));
2855 case 6:
2856 return (subr->function.a6
2857 (internal_args[0], internal_args[1], internal_args[2],
2858 internal_args[3], internal_args[4], internal_args[5]));
2859 case 7:
2860 return (subr->function.a7
2861 (internal_args[0], internal_args[1], internal_args[2],
2862 internal_args[3], internal_args[4], internal_args[5],
2863 internal_args[6]));
2864 case 8:
2865 return (subr->function.a8
2866 (internal_args[0], internal_args[1], internal_args[2],
2867 internal_args[3], internal_args[4], internal_args[5],
2868 internal_args[6], internal_args[7]));
2870 default:
2872 /* If a subr takes more than 8 arguments without using MANY
2873 or UNEVALLED, we need to extend this function to support it.
2874 Until this is done, there is no way to call the function. */
2875 emacs_abort ();
2880 static Lisp_Object
2881 apply_lambda (Lisp_Object fun, Lisp_Object args, ptrdiff_t count)
2883 Lisp_Object args_left;
2884 ptrdiff_t i;
2885 EMACS_INT numargs;
2886 Lisp_Object *arg_vector;
2887 Lisp_Object tem;
2888 USE_SAFE_ALLOCA;
2890 numargs = XFASTINT (Flength (args));
2891 SAFE_ALLOCA_LISP (arg_vector, numargs);
2892 args_left = args;
2894 for (i = 0; i < numargs; )
2896 tem = Fcar (args_left), args_left = Fcdr (args_left);
2897 tem = eval_sub (tem);
2898 arg_vector[i++] = tem;
2901 set_backtrace_args (specpdl + count, arg_vector, i);
2902 tem = funcall_lambda (fun, numargs, arg_vector);
2904 check_cons_list ();
2905 lisp_eval_depth--;
2906 /* Do the debug-on-exit now, while arg_vector still exists. */
2907 if (backtrace_debug_on_exit (specpdl + count))
2908 tem = call_debugger (list2 (Qexit, tem));
2909 SAFE_FREE ();
2910 specpdl_ptr--;
2911 return tem;
2914 /* Apply a Lisp function FUN to the NARGS evaluated arguments in ARG_VECTOR
2915 and return the result of evaluation.
2916 FUN must be either a lambda-expression or a compiled-code object. */
2918 static Lisp_Object
2919 funcall_lambda (Lisp_Object fun, ptrdiff_t nargs,
2920 register Lisp_Object *arg_vector)
2922 Lisp_Object val, syms_left, next, lexenv;
2923 ptrdiff_t count = SPECPDL_INDEX ();
2924 ptrdiff_t i;
2925 bool optional, rest;
2927 if (CONSP (fun))
2929 if (EQ (XCAR (fun), Qclosure))
2931 Lisp_Object cdr = XCDR (fun); /* Drop `closure'. */
2932 if (! CONSP (cdr))
2933 xsignal1 (Qinvalid_function, fun);
2934 fun = cdr;
2935 lexenv = XCAR (fun);
2937 else
2938 lexenv = Qnil;
2939 syms_left = XCDR (fun);
2940 if (CONSP (syms_left))
2941 syms_left = XCAR (syms_left);
2942 else
2943 xsignal1 (Qinvalid_function, fun);
2945 else if (COMPILEDP (fun))
2947 ptrdiff_t size = ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK;
2948 if (size <= COMPILED_STACK_DEPTH)
2949 xsignal1 (Qinvalid_function, fun);
2950 syms_left = AREF (fun, COMPILED_ARGLIST);
2951 if (INTEGERP (syms_left))
2952 /* A byte-code object with an integer args template means we
2953 shouldn't bind any arguments, instead just call the byte-code
2954 interpreter directly; it will push arguments as necessary.
2956 Byte-code objects with a nil args template (the default)
2957 have dynamically-bound arguments, and use the
2958 argument-binding code below instead (as do all interpreted
2959 functions, even lexically bound ones). */
2961 /* If we have not actually read the bytecode string
2962 and constants vector yet, fetch them from the file. */
2963 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2964 Ffetch_bytecode (fun);
2965 return exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2966 AREF (fun, COMPILED_CONSTANTS),
2967 AREF (fun, COMPILED_STACK_DEPTH),
2968 syms_left,
2969 nargs, arg_vector);
2971 lexenv = Qnil;
2973 else
2974 emacs_abort ();
2976 i = optional = rest = 0;
2977 bool previous_optional_or_rest = false;
2978 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
2980 maybe_quit ();
2982 next = XCAR (syms_left);
2983 if (!SYMBOLP (next))
2984 xsignal1 (Qinvalid_function, fun);
2986 if (EQ (next, Qand_rest))
2988 if (rest || previous_optional_or_rest)
2989 xsignal1 (Qinvalid_function, fun);
2990 rest = 1;
2991 previous_optional_or_rest = true;
2993 else if (EQ (next, Qand_optional))
2995 if (optional || rest || previous_optional_or_rest)
2996 xsignal1 (Qinvalid_function, fun);
2997 optional = 1;
2998 previous_optional_or_rest = true;
3000 else
3002 Lisp_Object arg;
3003 if (rest)
3005 arg = Flist (nargs - i, &arg_vector[i]);
3006 i = nargs;
3008 else if (i < nargs)
3009 arg = arg_vector[i++];
3010 else if (!optional)
3011 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
3012 else
3013 arg = Qnil;
3015 /* Bind the argument. */
3016 if (!NILP (lexenv) && SYMBOLP (next))
3017 /* Lexically bind NEXT by adding it to the lexenv alist. */
3018 lexenv = Fcons (Fcons (next, arg), lexenv);
3019 else
3020 /* Dynamically bind NEXT. */
3021 specbind (next, arg);
3022 previous_optional_or_rest = false;
3026 if (!NILP (syms_left) || previous_optional_or_rest)
3027 xsignal1 (Qinvalid_function, fun);
3028 else if (i < nargs)
3029 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
3031 if (!EQ (lexenv, Vinternal_interpreter_environment))
3032 /* Instantiate a new lexical environment. */
3033 specbind (Qinternal_interpreter_environment, lexenv);
3035 if (CONSP (fun))
3036 val = Fprogn (XCDR (XCDR (fun)));
3037 else
3039 /* If we have not actually read the bytecode string
3040 and constants vector yet, fetch them from the file. */
3041 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
3042 Ffetch_bytecode (fun);
3043 val = exec_byte_code (AREF (fun, COMPILED_BYTECODE),
3044 AREF (fun, COMPILED_CONSTANTS),
3045 AREF (fun, COMPILED_STACK_DEPTH),
3046 Qnil, 0, 0);
3049 return unbind_to (count, val);
3052 DEFUN ("func-arity", Ffunc_arity, Sfunc_arity, 1, 1, 0,
3053 doc: /* Return minimum and maximum number of args allowed for FUNCTION.
3054 FUNCTION must be a function of some kind.
3055 The returned value is a cons cell (MIN . MAX). MIN is the minimum number
3056 of args. MAX is the maximum number, or the symbol `many', for a
3057 function with `&rest' args, or `unevalled' for a special form. */)
3058 (Lisp_Object function)
3060 Lisp_Object original;
3061 Lisp_Object funcar;
3062 Lisp_Object result;
3064 original = function;
3066 retry:
3068 /* Optimize for no indirection. */
3069 function = original;
3070 if (SYMBOLP (function) && !NILP (function))
3072 function = XSYMBOL (function)->function;
3073 if (SYMBOLP (function))
3074 function = indirect_function (function);
3077 if (CONSP (function) && EQ (XCAR (function), Qmacro))
3078 function = XCDR (function);
3080 if (SUBRP (function))
3081 result = Fsubr_arity (function);
3082 else if (COMPILEDP (function))
3083 result = lambda_arity (function);
3084 else
3086 if (NILP (function))
3087 xsignal1 (Qvoid_function, original);
3088 if (!CONSP (function))
3089 xsignal1 (Qinvalid_function, original);
3090 funcar = XCAR (function);
3091 if (!SYMBOLP (funcar))
3092 xsignal1 (Qinvalid_function, original);
3093 if (EQ (funcar, Qlambda)
3094 || EQ (funcar, Qclosure))
3095 result = lambda_arity (function);
3096 else if (EQ (funcar, Qautoload))
3098 Fautoload_do_load (function, original, Qnil);
3099 goto retry;
3101 else
3102 xsignal1 (Qinvalid_function, original);
3104 return result;
3107 /* FUN must be either a lambda-expression or a compiled-code object. */
3108 static Lisp_Object
3109 lambda_arity (Lisp_Object fun)
3111 Lisp_Object syms_left;
3113 if (CONSP (fun))
3115 if (EQ (XCAR (fun), Qclosure))
3117 fun = XCDR (fun); /* Drop `closure'. */
3118 CHECK_CONS (fun);
3120 syms_left = XCDR (fun);
3121 if (CONSP (syms_left))
3122 syms_left = XCAR (syms_left);
3123 else
3124 xsignal1 (Qinvalid_function, fun);
3126 else if (COMPILEDP (fun))
3128 ptrdiff_t size = ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK;
3129 if (size <= COMPILED_STACK_DEPTH)
3130 xsignal1 (Qinvalid_function, fun);
3131 syms_left = AREF (fun, COMPILED_ARGLIST);
3132 if (INTEGERP (syms_left))
3133 return get_byte_code_arity (syms_left);
3135 else
3136 emacs_abort ();
3138 EMACS_INT minargs = 0, maxargs = 0;
3139 bool optional = false;
3140 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
3142 Lisp_Object next = XCAR (syms_left);
3143 if (!SYMBOLP (next))
3144 xsignal1 (Qinvalid_function, fun);
3146 if (EQ (next, Qand_rest))
3147 return Fcons (make_number (minargs), Qmany);
3148 else if (EQ (next, Qand_optional))
3149 optional = true;
3150 else
3152 if (!optional)
3153 minargs++;
3154 maxargs++;
3158 if (!NILP (syms_left))
3159 xsignal1 (Qinvalid_function, fun);
3161 return Fcons (make_number (minargs), make_number (maxargs));
3164 DEFUN ("fetch-bytecode", Ffetch_bytecode, Sfetch_bytecode,
3165 1, 1, 0,
3166 doc: /* If byte-compiled OBJECT is lazy-loaded, fetch it now. */)
3167 (Lisp_Object object)
3169 Lisp_Object tem;
3171 if (COMPILEDP (object))
3173 ptrdiff_t size = ASIZE (object) & PSEUDOVECTOR_SIZE_MASK;
3174 if (size <= COMPILED_STACK_DEPTH)
3175 xsignal1 (Qinvalid_function, object);
3176 if (CONSP (AREF (object, COMPILED_BYTECODE)))
3178 tem = read_doc_string (AREF (object, COMPILED_BYTECODE));
3179 if (!CONSP (tem))
3181 tem = AREF (object, COMPILED_BYTECODE);
3182 if (CONSP (tem) && STRINGP (XCAR (tem)))
3183 error ("Invalid byte code in %s", SDATA (XCAR (tem)));
3184 else
3185 error ("Invalid byte code");
3187 ASET (object, COMPILED_BYTECODE, XCAR (tem));
3188 ASET (object, COMPILED_CONSTANTS, XCDR (tem));
3191 return object;
3194 /* Return true if SYMBOL currently has a let-binding
3195 which was made in the buffer that is now current. */
3197 bool
3198 let_shadows_buffer_binding_p (struct Lisp_Symbol *symbol)
3200 union specbinding *p;
3201 Lisp_Object buf = Fcurrent_buffer ();
3203 for (p = specpdl_ptr; p > specpdl; )
3204 if ((--p)->kind > SPECPDL_LET)
3206 struct Lisp_Symbol *let_bound_symbol = XSYMBOL (specpdl_symbol (p));
3207 eassert (let_bound_symbol->redirect != SYMBOL_VARALIAS);
3208 if (symbol == let_bound_symbol
3209 && EQ (specpdl_where (p), buf))
3210 return 1;
3213 return 0;
3216 bool
3217 let_shadows_global_binding_p (Lisp_Object symbol)
3219 union specbinding *p;
3221 for (p = specpdl_ptr; p > specpdl; )
3222 if ((--p)->kind >= SPECPDL_LET && EQ (specpdl_symbol (p), symbol))
3223 return 1;
3225 return 0;
3228 static void
3229 do_specbind (struct Lisp_Symbol *sym, union specbinding *bind,
3230 Lisp_Object value, enum Set_Internal_Bind bindflag)
3232 switch (sym->redirect)
3234 case SYMBOL_PLAINVAL:
3235 if (!sym->trapped_write)
3236 SET_SYMBOL_VAL (sym, value);
3237 else
3238 set_internal (specpdl_symbol (bind), value, Qnil, bindflag);
3239 break;
3241 case SYMBOL_FORWARDED:
3242 if (BUFFER_OBJFWDP (SYMBOL_FWD (sym))
3243 && specpdl_kind (bind) == SPECPDL_LET_DEFAULT)
3245 set_default_internal (specpdl_symbol (bind), value, bindflag);
3246 return;
3248 /* FALLTHROUGH */
3249 case SYMBOL_LOCALIZED:
3250 set_internal (specpdl_symbol (bind), value, Qnil, bindflag);
3251 break;
3253 default:
3254 emacs_abort ();
3258 /* `specpdl_ptr' describes which variable is
3259 let-bound, so it can be properly undone when we unbind_to.
3260 It can be either a plain SPECPDL_LET or a SPECPDL_LET_LOCAL/DEFAULT.
3261 - SYMBOL is the variable being bound. Note that it should not be
3262 aliased (i.e. when let-binding V1 that's aliased to V2, we want
3263 to record V2 here).
3264 - WHERE tells us in which buffer the binding took place.
3265 This is used for SPECPDL_LET_LOCAL bindings (i.e. bindings to a
3266 buffer-local variable) as well as for SPECPDL_LET_DEFAULT bindings,
3267 i.e. bindings to the default value of a variable which can be
3268 buffer-local. */
3270 void
3271 specbind (Lisp_Object symbol, Lisp_Object value)
3273 struct Lisp_Symbol *sym;
3275 CHECK_SYMBOL (symbol);
3276 sym = XSYMBOL (symbol);
3278 start:
3279 switch (sym->redirect)
3281 case SYMBOL_VARALIAS:
3282 sym = indirect_variable (sym); XSETSYMBOL (symbol, sym); goto start;
3283 case SYMBOL_PLAINVAL:
3284 /* The most common case is that of a non-constant symbol with a
3285 trivial value. Make that as fast as we can. */
3286 specpdl_ptr->let.kind = SPECPDL_LET;
3287 specpdl_ptr->let.symbol = symbol;
3288 specpdl_ptr->let.old_value = SYMBOL_VAL (sym);
3289 specpdl_ptr->let.saved_value = Qnil;
3290 grow_specpdl ();
3291 do_specbind (sym, specpdl_ptr - 1, value, SET_INTERNAL_BIND);
3292 break;
3293 case SYMBOL_LOCALIZED:
3294 case SYMBOL_FORWARDED:
3296 Lisp_Object ovalue = find_symbol_value (symbol);
3297 specpdl_ptr->let.kind = SPECPDL_LET_LOCAL;
3298 specpdl_ptr->let.symbol = symbol;
3299 specpdl_ptr->let.old_value = ovalue;
3300 specpdl_ptr->let.where = Fcurrent_buffer ();
3301 specpdl_ptr->let.saved_value = Qnil;
3303 eassert (sym->redirect != SYMBOL_LOCALIZED
3304 || (EQ (SYMBOL_BLV (sym)->where, Fcurrent_buffer ())));
3306 if (sym->redirect == SYMBOL_LOCALIZED)
3308 if (!blv_found (SYMBOL_BLV (sym)))
3309 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3311 else if (BUFFER_OBJFWDP (SYMBOL_FWD (sym)))
3313 /* If SYMBOL is a per-buffer variable which doesn't have a
3314 buffer-local value here, make the `let' change the global
3315 value by changing the value of SYMBOL in all buffers not
3316 having their own value. This is consistent with what
3317 happens with other buffer-local variables. */
3318 if (NILP (Flocal_variable_p (symbol, Qnil)))
3320 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3321 grow_specpdl ();
3322 do_specbind (sym, specpdl_ptr - 1, value, SET_INTERNAL_BIND);
3323 return;
3326 else
3327 specpdl_ptr->let.kind = SPECPDL_LET;
3329 grow_specpdl ();
3330 do_specbind (sym, specpdl_ptr - 1, value, SET_INTERNAL_BIND);
3331 break;
3333 default: emacs_abort ();
3337 /* Push unwind-protect entries of various types. */
3339 void
3340 record_unwind_protect (void (*function) (Lisp_Object), Lisp_Object arg)
3342 specpdl_ptr->unwind.kind = SPECPDL_UNWIND;
3343 specpdl_ptr->unwind.func = function;
3344 specpdl_ptr->unwind.arg = arg;
3345 grow_specpdl ();
3348 void
3349 record_unwind_protect_ptr (void (*function) (void *), void *arg)
3351 specpdl_ptr->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3352 specpdl_ptr->unwind_ptr.func = function;
3353 specpdl_ptr->unwind_ptr.arg = arg;
3354 grow_specpdl ();
3357 void
3358 record_unwind_protect_int (void (*function) (int), int arg)
3360 specpdl_ptr->unwind_int.kind = SPECPDL_UNWIND_INT;
3361 specpdl_ptr->unwind_int.func = function;
3362 specpdl_ptr->unwind_int.arg = arg;
3363 grow_specpdl ();
3366 void
3367 record_unwind_protect_void (void (*function) (void))
3369 specpdl_ptr->unwind_void.kind = SPECPDL_UNWIND_VOID;
3370 specpdl_ptr->unwind_void.func = function;
3371 grow_specpdl ();
3374 void
3375 rebind_for_thread_switch (void)
3377 union specbinding *bind;
3379 for (bind = specpdl; bind != specpdl_ptr; ++bind)
3381 if (bind->kind >= SPECPDL_LET)
3383 Lisp_Object value = specpdl_saved_value (bind);
3384 Lisp_Object sym = specpdl_symbol (bind);
3385 bind->let.saved_value = Qnil;
3386 do_specbind (XSYMBOL (sym), bind, value,
3387 SET_INTERNAL_THREAD_SWITCH);
3392 static void
3393 do_one_unbind (union specbinding *this_binding, bool unwinding,
3394 enum Set_Internal_Bind bindflag)
3396 eassert (unwinding || this_binding->kind >= SPECPDL_LET);
3397 switch (this_binding->kind)
3399 case SPECPDL_UNWIND:
3400 this_binding->unwind.func (this_binding->unwind.arg);
3401 break;
3402 case SPECPDL_UNWIND_PTR:
3403 this_binding->unwind_ptr.func (this_binding->unwind_ptr.arg);
3404 break;
3405 case SPECPDL_UNWIND_INT:
3406 this_binding->unwind_int.func (this_binding->unwind_int.arg);
3407 break;
3408 case SPECPDL_UNWIND_VOID:
3409 this_binding->unwind_void.func ();
3410 break;
3411 case SPECPDL_BACKTRACE:
3412 break;
3413 case SPECPDL_LET:
3414 { /* If variable has a trivial value (no forwarding), and isn't
3415 trapped, we can just set it. */
3416 Lisp_Object sym = specpdl_symbol (this_binding);
3417 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3419 if (XSYMBOL (sym)->trapped_write == SYMBOL_UNTRAPPED_WRITE)
3420 SET_SYMBOL_VAL (XSYMBOL (sym), specpdl_old_value (this_binding));
3421 else
3422 set_internal (sym, specpdl_old_value (this_binding),
3423 Qnil, bindflag);
3424 break;
3426 else
3427 { /* FALLTHROUGH!!
3428 NOTE: we only ever come here if make_local_foo was used for
3429 the first time on this var within this let. */
3432 case SPECPDL_LET_DEFAULT:
3433 set_default_internal (specpdl_symbol (this_binding),
3434 specpdl_old_value (this_binding),
3435 bindflag);
3436 break;
3437 case SPECPDL_LET_LOCAL:
3439 Lisp_Object symbol = specpdl_symbol (this_binding);
3440 Lisp_Object where = specpdl_where (this_binding);
3441 Lisp_Object old_value = specpdl_old_value (this_binding);
3442 eassert (BUFFERP (where));
3444 /* If this was a local binding, reset the value in the appropriate
3445 buffer, but only if that buffer's binding still exists. */
3446 if (!NILP (Flocal_variable_p (symbol, where)))
3447 set_internal (symbol, old_value, where, bindflag);
3449 break;
3453 static void
3454 do_nothing (void)
3457 /* Push an unwind-protect entry that does nothing, so that
3458 set_unwind_protect_ptr can overwrite it later. */
3460 void
3461 record_unwind_protect_nothing (void)
3463 record_unwind_protect_void (do_nothing);
3466 /* Clear the unwind-protect entry COUNT, so that it does nothing.
3467 It need not be at the top of the stack. */
3469 void
3470 clear_unwind_protect (ptrdiff_t count)
3472 union specbinding *p = specpdl + count;
3473 p->unwind_void.kind = SPECPDL_UNWIND_VOID;
3474 p->unwind_void.func = do_nothing;
3477 /* Set the unwind-protect entry COUNT so that it invokes FUNC (ARG).
3478 It need not be at the top of the stack. Discard the entry's
3479 previous value without invoking it. */
3481 void
3482 set_unwind_protect (ptrdiff_t count, void (*func) (Lisp_Object),
3483 Lisp_Object arg)
3485 union specbinding *p = specpdl + count;
3486 p->unwind.kind = SPECPDL_UNWIND;
3487 p->unwind.func = func;
3488 p->unwind.arg = arg;
3491 void
3492 set_unwind_protect_ptr (ptrdiff_t count, void (*func) (void *), void *arg)
3494 union specbinding *p = specpdl + count;
3495 p->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3496 p->unwind_ptr.func = func;
3497 p->unwind_ptr.arg = arg;
3500 /* Pop and execute entries from the unwind-protect stack until the
3501 depth COUNT is reached. Return VALUE. */
3503 Lisp_Object
3504 unbind_to (ptrdiff_t count, Lisp_Object value)
3506 Lisp_Object quitf = Vquit_flag;
3508 Vquit_flag = Qnil;
3510 while (specpdl_ptr != specpdl + count)
3512 /* Copy the binding, and decrement specpdl_ptr, before we do
3513 the work to unbind it. We decrement first
3514 so that an error in unbinding won't try to unbind
3515 the same entry again, and we copy the binding first
3516 in case more bindings are made during some of the code we run. */
3518 union specbinding this_binding;
3519 this_binding = *--specpdl_ptr;
3521 do_one_unbind (&this_binding, true, SET_INTERNAL_UNBIND);
3524 if (NILP (Vquit_flag) && !NILP (quitf))
3525 Vquit_flag = quitf;
3527 return value;
3530 void
3531 unbind_for_thread_switch (struct thread_state *thr)
3533 union specbinding *bind;
3535 for (bind = thr->m_specpdl_ptr; bind > thr->m_specpdl;)
3537 if ((--bind)->kind >= SPECPDL_LET)
3539 Lisp_Object sym = specpdl_symbol (bind);
3540 bind->let.saved_value = find_symbol_value (sym);
3541 do_one_unbind (bind, false, SET_INTERNAL_THREAD_SWITCH);
3546 DEFUN ("special-variable-p", Fspecial_variable_p, Sspecial_variable_p, 1, 1, 0,
3547 doc: /* Return non-nil if SYMBOL's global binding has been declared special.
3548 A special variable is one that will be bound dynamically, even in a
3549 context where binding is lexical by default. */)
3550 (Lisp_Object symbol)
3552 CHECK_SYMBOL (symbol);
3553 return XSYMBOL (symbol)->declared_special ? Qt : Qnil;
3557 static union specbinding *
3558 get_backtrace_starting_at (Lisp_Object base)
3560 union specbinding *pdl = backtrace_top ();
3562 if (!NILP (base))
3563 { /* Skip up to `base'. */
3564 base = Findirect_function (base, Qt);
3565 while (backtrace_p (pdl)
3566 && !EQ (base, Findirect_function (backtrace_function (pdl), Qt)))
3567 pdl = backtrace_next (pdl);
3570 return pdl;
3573 static union specbinding *
3574 get_backtrace_frame (Lisp_Object nframes, Lisp_Object base)
3576 register EMACS_INT i;
3578 CHECK_NATNUM (nframes);
3579 union specbinding *pdl = get_backtrace_starting_at (base);
3581 /* Find the frame requested. */
3582 for (i = XFASTINT (nframes); i > 0 && backtrace_p (pdl); i--)
3583 pdl = backtrace_next (pdl);
3585 return pdl;
3588 static Lisp_Object
3589 backtrace_frame_apply (Lisp_Object function, union specbinding *pdl)
3591 if (!backtrace_p (pdl))
3592 return Qnil;
3594 Lisp_Object flags = Qnil;
3595 if (backtrace_debug_on_exit (pdl))
3596 flags = Fcons (QCdebug_on_exit, Fcons (Qt, Qnil));
3598 if (backtrace_nargs (pdl) == UNEVALLED)
3599 return call4 (function, Qnil, backtrace_function (pdl), *backtrace_args (pdl), flags);
3600 else
3602 Lisp_Object tem = Flist (backtrace_nargs (pdl), backtrace_args (pdl));
3603 return call4 (function, Qt, backtrace_function (pdl), tem, flags);
3607 DEFUN ("backtrace-debug", Fbacktrace_debug, Sbacktrace_debug, 2, 2, 0,
3608 doc: /* Set the debug-on-exit flag of eval frame LEVEL levels down to FLAG.
3609 The debugger is entered when that frame exits, if the flag is non-nil. */)
3610 (Lisp_Object level, Lisp_Object flag)
3612 CHECK_NUMBER (level);
3613 union specbinding *pdl = get_backtrace_frame(level, Qnil);
3615 if (backtrace_p (pdl))
3616 set_backtrace_debug_on_exit (pdl, !NILP (flag));
3618 return flag;
3621 DEFUN ("mapbacktrace", Fmapbacktrace, Smapbacktrace, 1, 2, 0,
3622 doc: /* Call FUNCTION for each frame in backtrace.
3623 If BASE is non-nil, it should be a function and iteration will start
3624 from its nearest activation frame.
3625 FUNCTION is called with 4 arguments: EVALD, FUNC, ARGS, and FLAGS. If
3626 a frame has not evaluated its arguments yet or is a special form,
3627 EVALD is nil and ARGS is a list of forms. If a frame has evaluated
3628 its arguments and called its function already, EVALD is t and ARGS is
3629 a list of values.
3630 FLAGS is a plist of properties of the current frame: currently, the
3631 only supported property is :debug-on-exit. `mapbacktrace' always
3632 returns nil. */)
3633 (Lisp_Object function, Lisp_Object base)
3635 union specbinding *pdl = get_backtrace_starting_at (base);
3637 while (backtrace_p (pdl))
3639 backtrace_frame_apply (function, pdl);
3640 pdl = backtrace_next (pdl);
3643 return Qnil;
3646 DEFUN ("backtrace-frame--internal", Fbacktrace_frame_internal,
3647 Sbacktrace_frame_internal, 3, 3, NULL,
3648 doc: /* Call FUNCTION on stack frame NFRAMES away from BASE.
3649 Return the result of FUNCTION, or nil if no matching frame could be found. */)
3650 (Lisp_Object function, Lisp_Object nframes, Lisp_Object base)
3652 return backtrace_frame_apply (function, get_backtrace_frame (nframes, base));
3655 /* For backtrace-eval, we want to temporarily unwind the last few elements of
3656 the specpdl stack, and then rewind them. We store the pre-unwind values
3657 directly in the pre-existing specpdl elements (i.e. we swap the current
3658 value and the old value stored in the specpdl), kind of like the inplace
3659 pointer-reversal trick. As it turns out, the rewind does the same as the
3660 unwind, except it starts from the other end of the specpdl stack, so we use
3661 the same function for both unwind and rewind. */
3662 static void
3663 backtrace_eval_unrewind (int distance)
3665 union specbinding *tmp = specpdl_ptr;
3666 int step = -1;
3667 if (distance < 0)
3668 { /* It's a rewind rather than unwind. */
3669 tmp += distance - 1;
3670 step = 1;
3671 distance = -distance;
3674 for (; distance > 0; distance--)
3676 tmp += step;
3677 switch (tmp->kind)
3679 /* FIXME: Ideally we'd like to "temporarily unwind" (some of) those
3680 unwind_protect, but the problem is that we don't know how to
3681 rewind them afterwards. */
3682 case SPECPDL_UNWIND:
3684 Lisp_Object oldarg = tmp->unwind.arg;
3685 if (tmp->unwind.func == set_buffer_if_live)
3686 tmp->unwind.arg = Fcurrent_buffer ();
3687 else if (tmp->unwind.func == save_excursion_restore)
3688 tmp->unwind.arg = save_excursion_save ();
3689 else
3690 break;
3691 tmp->unwind.func (oldarg);
3692 break;
3695 case SPECPDL_UNWIND_PTR:
3696 case SPECPDL_UNWIND_INT:
3697 case SPECPDL_UNWIND_VOID:
3698 case SPECPDL_BACKTRACE:
3699 break;
3700 case SPECPDL_LET:
3701 { /* If variable has a trivial value (no forwarding), we can
3702 just set it. No need to check for constant symbols here,
3703 since that was already done by specbind. */
3704 Lisp_Object sym = specpdl_symbol (tmp);
3705 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3707 Lisp_Object old_value = specpdl_old_value (tmp);
3708 set_specpdl_old_value (tmp, SYMBOL_VAL (XSYMBOL (sym)));
3709 SET_SYMBOL_VAL (XSYMBOL (sym), old_value);
3710 break;
3712 else
3713 { /* FALLTHROUGH!!
3714 NOTE: we only ever come here if make_local_foo was used for
3715 the first time on this var within this let. */
3718 case SPECPDL_LET_DEFAULT:
3720 Lisp_Object sym = specpdl_symbol (tmp);
3721 Lisp_Object old_value = specpdl_old_value (tmp);
3722 set_specpdl_old_value (tmp, Fdefault_value (sym));
3723 Fset_default (sym, old_value);
3725 break;
3726 case SPECPDL_LET_LOCAL:
3728 Lisp_Object symbol = specpdl_symbol (tmp);
3729 Lisp_Object where = specpdl_where (tmp);
3730 Lisp_Object old_value = specpdl_old_value (tmp);
3731 eassert (BUFFERP (where));
3733 /* If this was a local binding, reset the value in the appropriate
3734 buffer, but only if that buffer's binding still exists. */
3735 if (!NILP (Flocal_variable_p (symbol, where)))
3737 set_specpdl_old_value
3738 (tmp, Fbuffer_local_value (symbol, where));
3739 set_internal (symbol, old_value, where, SET_INTERNAL_UNBIND);
3742 break;
3747 DEFUN ("backtrace-eval", Fbacktrace_eval, Sbacktrace_eval, 2, 3, NULL,
3748 doc: /* Evaluate EXP in the context of some activation frame.
3749 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3750 (Lisp_Object exp, Lisp_Object nframes, Lisp_Object base)
3752 union specbinding *pdl = get_backtrace_frame (nframes, base);
3753 ptrdiff_t count = SPECPDL_INDEX ();
3754 ptrdiff_t distance = specpdl_ptr - pdl;
3755 eassert (distance >= 0);
3757 if (!backtrace_p (pdl))
3758 error ("Activation frame not found!");
3760 backtrace_eval_unrewind (distance);
3761 record_unwind_protect_int (backtrace_eval_unrewind, -distance);
3763 /* Use eval_sub rather than Feval since the main motivation behind
3764 backtrace-eval is to be able to get/set the value of lexical variables
3765 from the debugger. */
3766 return unbind_to (count, eval_sub (exp));
3769 DEFUN ("backtrace--locals", Fbacktrace__locals, Sbacktrace__locals, 1, 2, NULL,
3770 doc: /* Return names and values of local variables of a stack frame.
3771 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3772 (Lisp_Object nframes, Lisp_Object base)
3774 union specbinding *frame = get_backtrace_frame (nframes, base);
3775 union specbinding *prevframe
3776 = get_backtrace_frame (make_number (XFASTINT (nframes) - 1), base);
3777 ptrdiff_t distance = specpdl_ptr - frame;
3778 Lisp_Object result = Qnil;
3779 eassert (distance >= 0);
3781 if (!backtrace_p (prevframe))
3782 error ("Activation frame not found!");
3783 if (!backtrace_p (frame))
3784 error ("Activation frame not found!");
3786 /* The specpdl entries normally contain the symbol being bound along with its
3787 `old_value', so it can be restored. The new value to which it is bound is
3788 available in one of two places: either in the current value of the
3789 variable (if it hasn't been rebound yet) or in the `old_value' slot of the
3790 next specpdl entry for it.
3791 `backtrace_eval_unrewind' happens to swap the role of `old_value'
3792 and "new value", so we abuse it here, to fetch the new value.
3793 It's ugly (we'd rather not modify global data) and a bit inefficient,
3794 but it does the job for now. */
3795 backtrace_eval_unrewind (distance);
3797 /* Grab values. */
3799 union specbinding *tmp = prevframe;
3800 for (; tmp > frame; tmp--)
3802 switch (tmp->kind)
3804 case SPECPDL_LET:
3805 case SPECPDL_LET_DEFAULT:
3806 case SPECPDL_LET_LOCAL:
3808 Lisp_Object sym = specpdl_symbol (tmp);
3809 Lisp_Object val = specpdl_old_value (tmp);
3810 if (EQ (sym, Qinternal_interpreter_environment))
3812 Lisp_Object env = val;
3813 for (; CONSP (env); env = XCDR (env))
3815 Lisp_Object binding = XCAR (env);
3816 if (CONSP (binding))
3817 result = Fcons (Fcons (XCAR (binding),
3818 XCDR (binding)),
3819 result);
3822 else
3823 result = Fcons (Fcons (sym, val), result);
3825 break;
3827 case SPECPDL_UNWIND:
3828 case SPECPDL_UNWIND_PTR:
3829 case SPECPDL_UNWIND_INT:
3830 case SPECPDL_UNWIND_VOID:
3831 case SPECPDL_BACKTRACE:
3832 break;
3834 default:
3835 emacs_abort ();
3840 /* Restore values from specpdl to original place. */
3841 backtrace_eval_unrewind (-distance);
3843 return result;
3847 void
3848 mark_specpdl (union specbinding *first, union specbinding *ptr)
3850 union specbinding *pdl;
3851 for (pdl = first; pdl != ptr; pdl++)
3853 switch (pdl->kind)
3855 case SPECPDL_UNWIND:
3856 mark_object (specpdl_arg (pdl));
3857 break;
3859 case SPECPDL_BACKTRACE:
3861 ptrdiff_t nargs = backtrace_nargs (pdl);
3862 mark_object (backtrace_function (pdl));
3863 if (nargs == UNEVALLED)
3864 nargs = 1;
3865 while (nargs--)
3866 mark_object (backtrace_args (pdl)[nargs]);
3868 break;
3870 case SPECPDL_LET_DEFAULT:
3871 case SPECPDL_LET_LOCAL:
3872 mark_object (specpdl_where (pdl));
3873 /* Fall through. */
3874 case SPECPDL_LET:
3875 mark_object (specpdl_symbol (pdl));
3876 mark_object (specpdl_old_value (pdl));
3877 mark_object (specpdl_saved_value (pdl));
3878 break;
3880 case SPECPDL_UNWIND_PTR:
3881 case SPECPDL_UNWIND_INT:
3882 case SPECPDL_UNWIND_VOID:
3883 break;
3885 default:
3886 emacs_abort ();
3891 void
3892 get_backtrace (Lisp_Object array)
3894 union specbinding *pdl = backtrace_next (backtrace_top ());
3895 ptrdiff_t i = 0, asize = ASIZE (array);
3897 /* Copy the backtrace contents into working memory. */
3898 for (; i < asize; i++)
3900 if (backtrace_p (pdl))
3902 ASET (array, i, backtrace_function (pdl));
3903 pdl = backtrace_next (pdl);
3905 else
3906 ASET (array, i, Qnil);
3910 Lisp_Object backtrace_top_function (void)
3912 union specbinding *pdl = backtrace_top ();
3913 return (backtrace_p (pdl) ? backtrace_function (pdl) : Qnil);
3916 void
3917 syms_of_eval (void)
3919 DEFVAR_INT ("max-specpdl-size", max_specpdl_size,
3920 doc: /* Limit on number of Lisp variable bindings and `unwind-protect's.
3921 If Lisp code tries to increase the total number past this amount,
3922 an error is signaled.
3923 You can safely use a value considerably larger than the default value,
3924 if that proves inconveniently small. However, if you increase it too far,
3925 Emacs could run out of memory trying to make the stack bigger.
3926 Note that this limit may be silently increased by the debugger
3927 if `debug-on-error' or `debug-on-quit' is set. */);
3929 DEFVAR_INT ("max-lisp-eval-depth", max_lisp_eval_depth,
3930 doc: /* Limit on depth in `eval', `apply' and `funcall' before error.
3932 This limit serves to catch infinite recursions for you before they cause
3933 actual stack overflow in C, which would be fatal for Emacs.
3934 You can safely make it considerably larger than its default value,
3935 if that proves inconveniently small. However, if you increase it too far,
3936 Emacs could overflow the real C stack, and crash. */);
3938 DEFVAR_LISP ("quit-flag", Vquit_flag,
3939 doc: /* Non-nil causes `eval' to abort, unless `inhibit-quit' is non-nil.
3940 If the value is t, that means do an ordinary quit.
3941 If the value equals `throw-on-input', that means quit by throwing
3942 to the tag specified in `throw-on-input'; it's for handling `while-no-input'.
3943 Typing C-g sets `quit-flag' to t, regardless of `inhibit-quit',
3944 but `inhibit-quit' non-nil prevents anything from taking notice of that. */);
3945 Vquit_flag = Qnil;
3947 DEFVAR_LISP ("inhibit-quit", Vinhibit_quit,
3948 doc: /* Non-nil inhibits C-g quitting from happening immediately.
3949 Note that `quit-flag' will still be set by typing C-g,
3950 so a quit will be signaled as soon as `inhibit-quit' is nil.
3951 To prevent this happening, set `quit-flag' to nil
3952 before making `inhibit-quit' nil. */);
3953 Vinhibit_quit = Qnil;
3955 DEFSYM (Qsetq, "setq");
3956 DEFSYM (Qinhibit_quit, "inhibit-quit");
3957 DEFSYM (Qautoload, "autoload");
3958 DEFSYM (Qinhibit_debugger, "inhibit-debugger");
3959 DEFSYM (Qmacro, "macro");
3961 /* Note that the process handling also uses Qexit, but we don't want
3962 to staticpro it twice, so we just do it here. */
3963 DEFSYM (Qexit, "exit");
3965 DEFSYM (Qinteractive, "interactive");
3966 DEFSYM (Qcommandp, "commandp");
3967 DEFSYM (Qand_rest, "&rest");
3968 DEFSYM (Qand_optional, "&optional");
3969 DEFSYM (Qclosure, "closure");
3970 DEFSYM (QCdocumentation, ":documentation");
3971 DEFSYM (Qdebug, "debug");
3973 DEFVAR_LISP ("inhibit-debugger", Vinhibit_debugger,
3974 doc: /* Non-nil means never enter the debugger.
3975 Normally set while the debugger is already active, to avoid recursive
3976 invocations. */);
3977 Vinhibit_debugger = Qnil;
3979 DEFVAR_LISP ("debug-on-error", Vdebug_on_error,
3980 doc: /* Non-nil means enter debugger if an error is signaled.
3981 Does not apply to errors handled by `condition-case' or those
3982 matched by `debug-ignored-errors'.
3983 If the value is a list, an error only means to enter the debugger
3984 if one of its condition symbols appears in the list.
3985 When you evaluate an expression interactively, this variable
3986 is temporarily non-nil if `eval-expression-debug-on-error' is non-nil.
3987 The command `toggle-debug-on-error' toggles this.
3988 See also the variable `debug-on-quit' and `inhibit-debugger'. */);
3989 Vdebug_on_error = Qnil;
3991 DEFVAR_LISP ("debug-ignored-errors", Vdebug_ignored_errors,
3992 doc: /* List of errors for which the debugger should not be called.
3993 Each element may be a condition-name or a regexp that matches error messages.
3994 If any element applies to a given error, that error skips the debugger
3995 and just returns to top level.
3996 This overrides the variable `debug-on-error'.
3997 It does not apply to errors handled by `condition-case'. */);
3998 Vdebug_ignored_errors = Qnil;
4000 DEFVAR_BOOL ("debug-on-quit", debug_on_quit,
4001 doc: /* Non-nil means enter debugger if quit is signaled (C-g, for example).
4002 Does not apply if quit is handled by a `condition-case'. */);
4003 debug_on_quit = 0;
4005 DEFVAR_BOOL ("debug-on-next-call", debug_on_next_call,
4006 doc: /* Non-nil means enter debugger before next `eval', `apply' or `funcall'. */);
4008 DEFVAR_BOOL ("debugger-may-continue", debugger_may_continue,
4009 doc: /* Non-nil means debugger may continue execution.
4010 This is nil when the debugger is called under circumstances where it
4011 might not be safe to continue. */);
4012 debugger_may_continue = 1;
4014 DEFVAR_BOOL ("debugger-stack-frame-as-list", debugger_stack_frame_as_list,
4015 doc: /* Non-nil means display call stack frames as lists. */);
4016 debugger_stack_frame_as_list = 0;
4018 DEFVAR_LISP ("debugger", Vdebugger,
4019 doc: /* Function to call to invoke debugger.
4020 If due to frame exit, args are `exit' and the value being returned;
4021 this function's value will be returned instead of that.
4022 If due to error, args are `error' and a list of the args to `signal'.
4023 If due to `apply' or `funcall' entry, one arg, `lambda'.
4024 If due to `eval' entry, one arg, t. */);
4025 Vdebugger = Qnil;
4027 DEFVAR_LISP ("signal-hook-function", Vsignal_hook_function,
4028 doc: /* If non-nil, this is a function for `signal' to call.
4029 It receives the same arguments that `signal' was given.
4030 The Edebug package uses this to regain control. */);
4031 Vsignal_hook_function = Qnil;
4033 DEFVAR_LISP ("debug-on-signal", Vdebug_on_signal,
4034 doc: /* Non-nil means call the debugger regardless of condition handlers.
4035 Note that `debug-on-error', `debug-on-quit' and friends
4036 still determine whether to handle the particular condition. */);
4037 Vdebug_on_signal = Qnil;
4039 /* When lexical binding is being used,
4040 Vinternal_interpreter_environment is non-nil, and contains an alist
4041 of lexically-bound variable, or (t), indicating an empty
4042 environment. The lisp name of this variable would be
4043 `internal-interpreter-environment' if it weren't hidden.
4044 Every element of this list can be either a cons (VAR . VAL)
4045 specifying a lexical binding, or a single symbol VAR indicating
4046 that this variable should use dynamic scoping. */
4047 DEFSYM (Qinternal_interpreter_environment,
4048 "internal-interpreter-environment");
4049 DEFVAR_LISP ("internal-interpreter-environment",
4050 Vinternal_interpreter_environment,
4051 doc: /* If non-nil, the current lexical environment of the lisp interpreter.
4052 When lexical binding is not being used, this variable is nil.
4053 A value of `(t)' indicates an empty environment, otherwise it is an
4054 alist of active lexical bindings. */);
4055 Vinternal_interpreter_environment = Qnil;
4056 /* Don't export this variable to Elisp, so no one can mess with it
4057 (Just imagine if someone makes it buffer-local). */
4058 Funintern (Qinternal_interpreter_environment, Qnil);
4060 Vrun_hooks = intern_c_string ("run-hooks");
4061 staticpro (&Vrun_hooks);
4063 staticpro (&Vautoload_queue);
4064 Vautoload_queue = Qnil;
4065 staticpro (&Vsignaling_function);
4066 Vsignaling_function = Qnil;
4068 inhibit_lisp_code = Qnil;
4070 defsubr (&Sor);
4071 defsubr (&Sand);
4072 defsubr (&Sif);
4073 defsubr (&Scond);
4074 defsubr (&Sprogn);
4075 defsubr (&Sprog1);
4076 defsubr (&Sprog2);
4077 defsubr (&Ssetq);
4078 defsubr (&Squote);
4079 defsubr (&Sfunction);
4080 defsubr (&Sdefault_toplevel_value);
4081 defsubr (&Sset_default_toplevel_value);
4082 defsubr (&Sdefvar);
4083 defsubr (&Sdefvaralias);
4084 DEFSYM (Qdefvaralias, "defvaralias");
4085 defsubr (&Sdefconst);
4086 defsubr (&Smake_var_non_special);
4087 defsubr (&Slet);
4088 defsubr (&SletX);
4089 defsubr (&Swhile);
4090 defsubr (&Smacroexpand);
4091 defsubr (&Scatch);
4092 defsubr (&Sthrow);
4093 defsubr (&Sunwind_protect);
4094 defsubr (&Scondition_case);
4095 defsubr (&Ssignal);
4096 defsubr (&Scommandp);
4097 defsubr (&Sautoload);
4098 defsubr (&Sautoload_do_load);
4099 defsubr (&Seval);
4100 defsubr (&Sapply);
4101 defsubr (&Sfuncall);
4102 defsubr (&Sfunc_arity);
4103 defsubr (&Srun_hooks);
4104 defsubr (&Srun_hook_with_args);
4105 defsubr (&Srun_hook_with_args_until_success);
4106 defsubr (&Srun_hook_with_args_until_failure);
4107 defsubr (&Srun_hook_wrapped);
4108 defsubr (&Sfetch_bytecode);
4109 defsubr (&Sbacktrace_debug);
4110 DEFSYM (QCdebug_on_exit, ":debug-on-exit");
4111 defsubr (&Smapbacktrace);
4112 defsubr (&Sbacktrace_frame_internal);
4113 defsubr (&Sbacktrace_eval);
4114 defsubr (&Sbacktrace__locals);
4115 defsubr (&Sspecial_variable_p);
4116 defsubr (&Sfunctionp);