Merge from origin/emacs-25
[emacs.git] / src / eval.c
blob8ad06dded80066996abc7b682eb921110b6c5631
1 /* Evaluator for GNU Emacs Lisp interpreter.
3 Copyright (C) 1985-1987, 1993-1995, 1999-2016 Free Software Foundation,
4 Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
23 #include <limits.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include "lisp.h"
27 #include "blockinput.h"
28 #include "commands.h"
29 #include "keyboard.h"
30 #include "dispextern.h"
31 #include "buffer.h"
33 /* Chain of condition and catch handlers currently in effect. */
35 struct handler *handlerlist;
37 /* Non-nil means record all fset's and provide's, to be undone
38 if the file being autoloaded is not fully loaded.
39 They are recorded by being consed onto the front of Vautoload_queue:
40 (FUN . ODEF) for a defun, (0 . OFEATURES) for a provide. */
42 Lisp_Object Vautoload_queue;
44 /* This holds either the symbol `run-hooks' or nil.
45 It is nil at an early stage of startup, and when Emacs
46 is shutting down. */
47 Lisp_Object Vrun_hooks;
49 /* Current number of specbindings allocated in specpdl, not counting
50 the dummy entry specpdl[-1]. */
52 ptrdiff_t specpdl_size;
54 /* Pointer to beginning of specpdl. A dummy entry specpdl[-1] exists
55 only so that its address can be taken. */
57 union specbinding *specpdl;
59 /* Pointer to first unused element in specpdl. */
61 union specbinding *specpdl_ptr;
63 /* Depth in Lisp evaluations and function calls. */
65 static EMACS_INT lisp_eval_depth;
67 /* The value of num_nonmacro_input_events as of the last time we
68 started to enter the debugger. If we decide to enter the debugger
69 again when this is still equal to num_nonmacro_input_events, then we
70 know that the debugger itself has an error, and we should just
71 signal the error instead of entering an infinite loop of debugger
72 invocations. */
74 static EMACS_INT when_entered_debugger;
76 /* The function from which the last `signal' was called. Set in
77 Fsignal. */
78 /* FIXME: We should probably get rid of this! */
79 Lisp_Object Vsignaling_function;
81 /* If non-nil, Lisp code must not be run since some part of Emacs is in
82 an inconsistent state. Currently unused. */
83 Lisp_Object inhibit_lisp_code;
85 /* These would ordinarily be static, but they need to be visible to GDB. */
86 bool backtrace_p (union specbinding *) EXTERNALLY_VISIBLE;
87 Lisp_Object *backtrace_args (union specbinding *) EXTERNALLY_VISIBLE;
88 Lisp_Object backtrace_function (union specbinding *) EXTERNALLY_VISIBLE;
89 union specbinding *backtrace_next (union specbinding *) EXTERNALLY_VISIBLE;
90 union specbinding *backtrace_top (void) EXTERNALLY_VISIBLE;
92 static Lisp_Object funcall_lambda (Lisp_Object, ptrdiff_t, Lisp_Object *);
93 static Lisp_Object apply_lambda (Lisp_Object, Lisp_Object, ptrdiff_t);
94 static Lisp_Object lambda_arity (Lisp_Object);
96 static Lisp_Object
97 specpdl_symbol (union specbinding *pdl)
99 eassert (pdl->kind >= SPECPDL_LET);
100 return pdl->let.symbol;
103 static Lisp_Object
104 specpdl_old_value (union specbinding *pdl)
106 eassert (pdl->kind >= SPECPDL_LET);
107 return pdl->let.old_value;
110 static void
111 set_specpdl_old_value (union specbinding *pdl, Lisp_Object val)
113 eassert (pdl->kind >= SPECPDL_LET);
114 pdl->let.old_value = val;
117 static Lisp_Object
118 specpdl_where (union specbinding *pdl)
120 eassert (pdl->kind > SPECPDL_LET);
121 return pdl->let.where;
124 static Lisp_Object
125 specpdl_arg (union specbinding *pdl)
127 eassert (pdl->kind == SPECPDL_UNWIND);
128 return pdl->unwind.arg;
131 Lisp_Object
132 backtrace_function (union specbinding *pdl)
134 eassert (pdl->kind == SPECPDL_BACKTRACE);
135 return pdl->bt.function;
138 static ptrdiff_t
139 backtrace_nargs (union specbinding *pdl)
141 eassert (pdl->kind == SPECPDL_BACKTRACE);
142 return pdl->bt.nargs;
145 Lisp_Object *
146 backtrace_args (union specbinding *pdl)
148 eassert (pdl->kind == SPECPDL_BACKTRACE);
149 return pdl->bt.args;
152 static bool
153 backtrace_debug_on_exit (union specbinding *pdl)
155 eassert (pdl->kind == SPECPDL_BACKTRACE);
156 return pdl->bt.debug_on_exit;
159 /* Functions to modify slots of backtrace records. */
161 static void
162 set_backtrace_args (union specbinding *pdl, Lisp_Object *args, ptrdiff_t nargs)
164 eassert (pdl->kind == SPECPDL_BACKTRACE);
165 pdl->bt.args = args;
166 pdl->bt.nargs = nargs;
169 static void
170 set_backtrace_debug_on_exit (union specbinding *pdl, bool doe)
172 eassert (pdl->kind == SPECPDL_BACKTRACE);
173 pdl->bt.debug_on_exit = doe;
176 /* Helper functions to scan the backtrace. */
178 bool
179 backtrace_p (union specbinding *pdl)
180 { return pdl >= specpdl; }
182 union specbinding *
183 backtrace_top (void)
185 union specbinding *pdl = specpdl_ptr - 1;
186 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
187 pdl--;
188 return pdl;
191 union specbinding *
192 backtrace_next (union specbinding *pdl)
194 pdl--;
195 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
196 pdl--;
197 return pdl;
200 /* Return a pointer to somewhere near the top of the C stack. */
201 void *
202 near_C_stack_top (void)
204 return backtrace_args (backtrace_top ());
207 void
208 init_eval_once (void)
210 enum { size = 50 };
211 union specbinding *pdlvec = xmalloc ((size + 1) * sizeof *specpdl);
212 specpdl_size = size;
213 specpdl = specpdl_ptr = pdlvec + 1;
214 /* Don't forget to update docs (lispref node "Local Variables"). */
215 max_specpdl_size = 1300; /* 1000 is not enough for CEDET's c-by.el. */
216 max_lisp_eval_depth = 800;
218 Vrun_hooks = Qnil;
221 static struct handler handlerlist_sentinel;
223 void
224 init_eval (void)
226 specpdl_ptr = specpdl;
227 { /* Put a dummy catcher at top-level so that handlerlist is never NULL.
228 This is important since handlerlist->nextfree holds the freelist
229 which would otherwise leak every time we unwind back to top-level. */
230 handlerlist = handlerlist_sentinel.nextfree = &handlerlist_sentinel;
231 struct handler *c = push_handler (Qunbound, CATCHER);
232 eassert (c == &handlerlist_sentinel);
233 handlerlist_sentinel.nextfree = NULL;
234 handlerlist_sentinel.next = NULL;
236 Vquit_flag = Qnil;
237 debug_on_next_call = 0;
238 lisp_eval_depth = 0;
239 /* This is less than the initial value of num_nonmacro_input_events. */
240 when_entered_debugger = -1;
243 /* Unwind-protect function used by call_debugger. */
245 static void
246 restore_stack_limits (Lisp_Object data)
248 max_specpdl_size = XINT (XCAR (data));
249 max_lisp_eval_depth = XINT (XCDR (data));
252 static void grow_specpdl (void);
254 /* Call the Lisp debugger, giving it argument ARG. */
256 Lisp_Object
257 call_debugger (Lisp_Object arg)
259 bool debug_while_redisplaying;
260 ptrdiff_t count = SPECPDL_INDEX ();
261 Lisp_Object val;
262 EMACS_INT old_depth = max_lisp_eval_depth;
263 /* Do not allow max_specpdl_size less than actual depth (Bug#16603). */
264 EMACS_INT old_max = max (max_specpdl_size, count);
266 if (lisp_eval_depth + 40 > max_lisp_eval_depth)
267 max_lisp_eval_depth = lisp_eval_depth + 40;
269 /* While debugging Bug#16603, previous value of 100 was found
270 too small to avoid specpdl overflow in the debugger itself. */
271 if (max_specpdl_size - 200 < count)
272 max_specpdl_size = count + 200;
274 if (old_max == count)
276 /* We can enter the debugger due to specpdl overflow (Bug#16603). */
277 specpdl_ptr--;
278 grow_specpdl ();
281 /* Restore limits after leaving the debugger. */
282 record_unwind_protect (restore_stack_limits,
283 Fcons (make_number (old_max),
284 make_number (old_depth)));
286 #ifdef HAVE_WINDOW_SYSTEM
287 if (display_hourglass_p)
288 cancel_hourglass ();
289 #endif
291 debug_on_next_call = 0;
292 when_entered_debugger = num_nonmacro_input_events;
294 /* Resetting redisplaying_p to 0 makes sure that debug output is
295 displayed if the debugger is invoked during redisplay. */
296 debug_while_redisplaying = redisplaying_p;
297 redisplaying_p = 0;
298 specbind (intern ("debugger-may-continue"),
299 debug_while_redisplaying ? Qnil : Qt);
300 specbind (Qinhibit_redisplay, Qnil);
301 specbind (Qinhibit_debugger, Qt);
303 /* If we are debugging an error while `inhibit-changing-match-data'
304 is bound to non-nil (e.g., within a call to `string-match-p'),
305 then make sure debugger code can still use match data. */
306 specbind (Qinhibit_changing_match_data, Qnil);
308 #if 0 /* Binding this prevents execution of Lisp code during
309 redisplay, which necessarily leads to display problems. */
310 specbind (Qinhibit_eval_during_redisplay, Qt);
311 #endif
313 val = apply1 (Vdebugger, arg);
315 /* Interrupting redisplay and resuming it later is not safe under
316 all circumstances. So, when the debugger returns, abort the
317 interrupted redisplay by going back to the top-level. */
318 if (debug_while_redisplaying)
319 Ftop_level ();
321 return unbind_to (count, val);
324 static void
325 do_debug_on_call (Lisp_Object code, ptrdiff_t count)
327 debug_on_next_call = 0;
328 set_backtrace_debug_on_exit (specpdl + count, true);
329 call_debugger (list1 (code));
332 /* NOTE!!! Every function that can call EVAL must protect its args
333 and temporaries from garbage collection while it needs them.
334 The definition of `For' shows what you have to do. */
336 DEFUN ("or", For, Sor, 0, UNEVALLED, 0,
337 doc: /* Eval args until one of them yields non-nil, then return that value.
338 The remaining args are not evalled at all.
339 If all args return nil, return nil.
340 usage: (or CONDITIONS...) */)
341 (Lisp_Object args)
343 Lisp_Object val = Qnil;
345 while (CONSP (args))
347 val = eval_sub (XCAR (args));
348 if (!NILP (val))
349 break;
350 args = XCDR (args);
353 return val;
356 DEFUN ("and", Fand, Sand, 0, UNEVALLED, 0,
357 doc: /* Eval args until one of them yields nil, then return nil.
358 The remaining args are not evalled at all.
359 If no arg yields nil, return the last arg's value.
360 usage: (and CONDITIONS...) */)
361 (Lisp_Object args)
363 Lisp_Object val = Qt;
365 while (CONSP (args))
367 val = eval_sub (XCAR (args));
368 if (NILP (val))
369 break;
370 args = XCDR (args);
373 return val;
376 DEFUN ("if", Fif, Sif, 2, UNEVALLED, 0,
377 doc: /* If COND yields non-nil, do THEN, else do ELSE...
378 Returns the value of THEN or the value of the last of the ELSE's.
379 THEN must be one expression, but ELSE... can be zero or more expressions.
380 If COND yields nil, and there are no ELSE's, the value is nil.
381 usage: (if COND THEN ELSE...) */)
382 (Lisp_Object args)
384 Lisp_Object cond;
386 cond = eval_sub (XCAR (args));
388 if (!NILP (cond))
389 return eval_sub (Fcar (XCDR (args)));
390 return Fprogn (XCDR (XCDR (args)));
393 DEFUN ("cond", Fcond, Scond, 0, UNEVALLED, 0,
394 doc: /* Try each clause until one succeeds.
395 Each clause looks like (CONDITION BODY...). CONDITION is evaluated
396 and, if the value is non-nil, this clause succeeds:
397 then the expressions in BODY are evaluated and the last one's
398 value is the value of the cond-form.
399 If a clause has one element, as in (CONDITION), then the cond-form
400 returns CONDITION's value, if that is non-nil.
401 If no clause succeeds, cond returns nil.
402 usage: (cond CLAUSES...) */)
403 (Lisp_Object args)
405 Lisp_Object val = args;
407 while (CONSP (args))
409 Lisp_Object clause = XCAR (args);
410 val = eval_sub (Fcar (clause));
411 if (!NILP (val))
413 if (!NILP (XCDR (clause)))
414 val = Fprogn (XCDR (clause));
415 break;
417 args = XCDR (args);
420 return val;
423 DEFUN ("progn", Fprogn, Sprogn, 0, UNEVALLED, 0,
424 doc: /* Eval BODY forms sequentially and return value of last one.
425 usage: (progn BODY...) */)
426 (Lisp_Object body)
428 Lisp_Object val = Qnil;
430 while (CONSP (body))
432 val = eval_sub (XCAR (body));
433 body = XCDR (body);
436 return val;
439 /* Evaluate BODY sequentially, discarding its value. Suitable for
440 record_unwind_protect. */
442 void
443 unwind_body (Lisp_Object body)
445 Fprogn (body);
448 DEFUN ("prog1", Fprog1, Sprog1, 1, UNEVALLED, 0,
449 doc: /* Eval FIRST and BODY sequentially; return value from FIRST.
450 The value of FIRST is saved during the evaluation of the remaining args,
451 whose values are discarded.
452 usage: (prog1 FIRST BODY...) */)
453 (Lisp_Object args)
455 Lisp_Object val;
456 Lisp_Object args_left;
458 args_left = args;
459 val = args;
461 val = eval_sub (XCAR (args_left));
462 while (CONSP (args_left = XCDR (args_left)))
463 eval_sub (XCAR (args_left));
465 return val;
468 DEFUN ("prog2", Fprog2, Sprog2, 2, UNEVALLED, 0,
469 doc: /* Eval FORM1, FORM2 and BODY sequentially; return value from FORM2.
470 The value of FORM2 is saved during the evaluation of the
471 remaining args, whose values are discarded.
472 usage: (prog2 FORM1 FORM2 BODY...) */)
473 (Lisp_Object args)
475 eval_sub (XCAR (args));
476 return Fprog1 (XCDR (args));
479 DEFUN ("setq", Fsetq, Ssetq, 0, UNEVALLED, 0,
480 doc: /* Set each SYM to the value of its VAL.
481 The symbols SYM are variables; they are literal (not evaluated).
482 The values VAL are expressions; they are evaluated.
483 Thus, (setq x (1+ y)) sets `x' to the value of `(1+ y)'.
484 The second VAL is not computed until after the first SYM is set, and so on;
485 each VAL can use the new value of variables set earlier in the `setq'.
486 The return value of the `setq' form is the value of the last VAL.
487 usage: (setq [SYM VAL]...) */)
488 (Lisp_Object args)
490 Lisp_Object val, sym, lex_binding;
492 val = args;
493 if (CONSP (args))
495 Lisp_Object args_left = args;
496 Lisp_Object numargs = Flength (args);
498 if (XINT (numargs) & 1)
499 xsignal2 (Qwrong_number_of_arguments, Qsetq, numargs);
503 val = eval_sub (Fcar (XCDR (args_left)));
504 sym = XCAR (args_left);
506 /* Like for eval_sub, we do not check declared_special here since
507 it's been done when let-binding. */
508 if (!NILP (Vinternal_interpreter_environment) /* Mere optimization! */
509 && SYMBOLP (sym)
510 && !NILP (lex_binding
511 = Fassq (sym, Vinternal_interpreter_environment)))
512 XSETCDR (lex_binding, val); /* SYM is lexically bound. */
513 else
514 Fset (sym, val); /* SYM is dynamically bound. */
516 args_left = Fcdr (XCDR (args_left));
518 while (CONSP (args_left));
521 return val;
524 DEFUN ("quote", Fquote, Squote, 1, UNEVALLED, 0,
525 doc: /* Return the argument, without evaluating it. `(quote x)' yields `x'.
526 Warning: `quote' does not construct its return value, but just returns
527 the value that was pre-constructed by the Lisp reader (see info node
528 `(elisp)Printed Representation').
529 This means that \\='(a . b) is not identical to (cons \\='a \\='b): the former
530 does not cons. Quoting should be reserved for constants that will
531 never be modified by side-effects, unless you like self-modifying code.
532 See the common pitfall in info node `(elisp)Rearrangement' for an example
533 of unexpected results when a quoted object is modified.
534 usage: (quote ARG) */)
535 (Lisp_Object args)
537 if (CONSP (XCDR (args)))
538 xsignal2 (Qwrong_number_of_arguments, Qquote, Flength (args));
539 return XCAR (args);
542 DEFUN ("function", Ffunction, Sfunction, 1, UNEVALLED, 0,
543 doc: /* Like `quote', but preferred for objects which are functions.
544 In byte compilation, `function' causes its argument to be compiled.
545 `quote' cannot do that.
546 usage: (function ARG) */)
547 (Lisp_Object args)
549 Lisp_Object quoted = XCAR (args);
551 if (CONSP (XCDR (args)))
552 xsignal2 (Qwrong_number_of_arguments, Qfunction, Flength (args));
554 if (!NILP (Vinternal_interpreter_environment)
555 && CONSP (quoted)
556 && EQ (XCAR (quoted), Qlambda))
557 { /* This is a lambda expression within a lexical environment;
558 return an interpreted closure instead of a simple lambda. */
559 Lisp_Object cdr = XCDR (quoted);
560 Lisp_Object tmp = cdr;
561 if (CONSP (tmp)
562 && (tmp = XCDR (tmp), CONSP (tmp))
563 && (tmp = XCAR (tmp), CONSP (tmp))
564 && (EQ (QCdocumentation, XCAR (tmp))))
565 { /* Handle the special (:documentation <form>) to build the docstring
566 dynamically. */
567 Lisp_Object docstring = eval_sub (Fcar (XCDR (tmp)));
568 CHECK_STRING (docstring);
569 cdr = Fcons (XCAR (cdr), Fcons (docstring, XCDR (XCDR (cdr))));
571 return Fcons (Qclosure, Fcons (Vinternal_interpreter_environment,
572 cdr));
574 else
575 /* Simply quote the argument. */
576 return quoted;
580 DEFUN ("defvaralias", Fdefvaralias, Sdefvaralias, 2, 3, 0,
581 doc: /* Make NEW-ALIAS a variable alias for symbol BASE-VARIABLE.
582 Aliased variables always have the same value; setting one sets the other.
583 Third arg DOCSTRING, if non-nil, is documentation for NEW-ALIAS. If it is
584 omitted or nil, NEW-ALIAS gets the documentation string of BASE-VARIABLE,
585 or of the variable at the end of the chain of aliases, if BASE-VARIABLE is
586 itself an alias. If NEW-ALIAS is bound, and BASE-VARIABLE is not,
587 then the value of BASE-VARIABLE is set to that of NEW-ALIAS.
588 The return value is BASE-VARIABLE. */)
589 (Lisp_Object new_alias, Lisp_Object base_variable, Lisp_Object docstring)
591 struct Lisp_Symbol *sym;
593 CHECK_SYMBOL (new_alias);
594 CHECK_SYMBOL (base_variable);
596 if (SYMBOL_CONSTANT_P (new_alias))
597 /* Making it an alias effectively changes its value. */
598 error ("Cannot make a constant an alias");
600 sym = XSYMBOL (new_alias);
602 switch (sym->redirect)
604 case SYMBOL_FORWARDED:
605 error ("Cannot make an internal variable an alias");
606 case SYMBOL_LOCALIZED:
607 error ("Don't know how to make a localized variable an alias");
608 case SYMBOL_PLAINVAL:
609 case SYMBOL_VARALIAS:
610 break;
611 default:
612 emacs_abort ();
615 /* http://lists.gnu.org/archive/html/emacs-devel/2008-04/msg00834.html
616 If n_a is bound, but b_v is not, set the value of b_v to n_a,
617 so that old-code that affects n_a before the aliasing is setup
618 still works. */
619 if (NILP (Fboundp (base_variable)))
620 set_internal (base_variable, find_symbol_value (new_alias),
621 Qnil, SET_INTERNAL_BIND);
623 union specbinding *p;
625 for (p = specpdl_ptr; p > specpdl; )
626 if ((--p)->kind >= SPECPDL_LET
627 && (EQ (new_alias, specpdl_symbol (p))))
628 error ("Don't know how to make a let-bound variable an alias");
631 if (sym->trapped_write == SYMBOL_TRAPPED_WRITE)
632 notify_variable_watchers (new_alias, base_variable, Qdefvaralias, Qnil);
634 sym->declared_special = 1;
635 XSYMBOL (base_variable)->declared_special = 1;
636 sym->redirect = SYMBOL_VARALIAS;
637 SET_SYMBOL_ALIAS (sym, XSYMBOL (base_variable));
638 sym->trapped_write = XSYMBOL (base_variable)->trapped_write;
639 LOADHIST_ATTACH (new_alias);
640 /* Even if docstring is nil: remove old docstring. */
641 Fput (new_alias, Qvariable_documentation, docstring);
643 return base_variable;
646 static union specbinding *
647 default_toplevel_binding (Lisp_Object symbol)
649 union specbinding *binding = NULL;
650 union specbinding *pdl = specpdl_ptr;
651 while (pdl > specpdl)
653 switch ((--pdl)->kind)
655 case SPECPDL_LET_DEFAULT:
656 case SPECPDL_LET:
657 if (EQ (specpdl_symbol (pdl), symbol))
658 binding = pdl;
659 break;
661 case SPECPDL_UNWIND:
662 case SPECPDL_UNWIND_PTR:
663 case SPECPDL_UNWIND_INT:
664 case SPECPDL_UNWIND_VOID:
665 case SPECPDL_BACKTRACE:
666 case SPECPDL_LET_LOCAL:
667 break;
669 default:
670 emacs_abort ();
673 return binding;
676 DEFUN ("default-toplevel-value", Fdefault_toplevel_value, Sdefault_toplevel_value, 1, 1, 0,
677 doc: /* Return SYMBOL's toplevel default value.
678 "Toplevel" means outside of any let binding. */)
679 (Lisp_Object symbol)
681 union specbinding *binding = default_toplevel_binding (symbol);
682 Lisp_Object value
683 = binding ? specpdl_old_value (binding) : Fdefault_value (symbol);
684 if (!EQ (value, Qunbound))
685 return value;
686 xsignal1 (Qvoid_variable, symbol);
689 DEFUN ("set-default-toplevel-value", Fset_default_toplevel_value,
690 Sset_default_toplevel_value, 2, 2, 0,
691 doc: /* Set SYMBOL's toplevel default value to VALUE.
692 "Toplevel" means outside of any let binding. */)
693 (Lisp_Object symbol, Lisp_Object value)
695 union specbinding *binding = default_toplevel_binding (symbol);
696 if (binding)
697 set_specpdl_old_value (binding, value);
698 else
699 Fset_default (symbol, value);
700 return Qnil;
703 DEFUN ("defvar", Fdefvar, Sdefvar, 1, UNEVALLED, 0,
704 doc: /* Define SYMBOL as a variable, and return SYMBOL.
705 You are not required to define a variable in order to use it, but
706 defining it lets you supply an initial value and documentation, which
707 can be referred to by the Emacs help facilities and other programming
708 tools. The `defvar' form also declares the variable as \"special\",
709 so that it is always dynamically bound even if `lexical-binding' is t.
711 The optional argument INITVALUE is evaluated, and used to set SYMBOL,
712 only if SYMBOL's value is void. If SYMBOL is buffer-local, its
713 default value is what is set; buffer-local values are not affected.
714 If INITVALUE is missing, SYMBOL's value is not set.
716 If SYMBOL has a local binding, then this form affects the local
717 binding. This is usually not what you want. Thus, if you need to
718 load a file defining variables, with this form or with `defconst' or
719 `defcustom', you should always load that file _outside_ any bindings
720 for these variables. (`defconst' and `defcustom' behave similarly in
721 this respect.)
723 The optional argument DOCSTRING is a documentation string for the
724 variable.
726 To define a user option, use `defcustom' instead of `defvar'.
727 usage: (defvar SYMBOL &optional INITVALUE DOCSTRING) */)
728 (Lisp_Object args)
730 Lisp_Object sym, tem, tail;
732 sym = XCAR (args);
733 tail = XCDR (args);
735 if (CONSP (tail))
737 if (CONSP (XCDR (tail)) && CONSP (XCDR (XCDR (tail))))
738 error ("Too many arguments");
740 tem = Fdefault_boundp (sym);
742 /* Do it before evaluating the initial value, for self-references. */
743 XSYMBOL (sym)->declared_special = 1;
745 if (NILP (tem))
746 Fset_default (sym, eval_sub (XCAR (tail)));
747 else
748 { /* Check if there is really a global binding rather than just a let
749 binding that shadows the global unboundness of the var. */
750 union specbinding *binding = default_toplevel_binding (sym);
751 if (binding && EQ (specpdl_old_value (binding), Qunbound))
753 set_specpdl_old_value (binding, eval_sub (XCAR (tail)));
756 tail = XCDR (tail);
757 tem = Fcar (tail);
758 if (!NILP (tem))
760 if (!NILP (Vpurify_flag))
761 tem = Fpurecopy (tem);
762 Fput (sym, Qvariable_documentation, tem);
764 LOADHIST_ATTACH (sym);
766 else if (!NILP (Vinternal_interpreter_environment)
767 && !XSYMBOL (sym)->declared_special)
768 /* A simple (defvar foo) with lexical scoping does "nothing" except
769 declare that var to be dynamically scoped *locally* (i.e. within
770 the current file or let-block). */
771 Vinternal_interpreter_environment
772 = Fcons (sym, Vinternal_interpreter_environment);
773 else
775 /* Simple (defvar <var>) should not count as a definition at all.
776 It could get in the way of other definitions, and unloading this
777 package could try to make the variable unbound. */
780 return sym;
783 DEFUN ("defconst", Fdefconst, Sdefconst, 2, UNEVALLED, 0,
784 doc: /* Define SYMBOL as a constant variable.
785 This declares that neither programs nor users should ever change the
786 value. This constancy is not actually enforced by Emacs Lisp, but
787 SYMBOL is marked as a special variable so that it is never lexically
788 bound.
790 The `defconst' form always sets the value of SYMBOL to the result of
791 evalling INITVALUE. If SYMBOL is buffer-local, its default value is
792 what is set; buffer-local values are not affected. If SYMBOL has a
793 local binding, then this form sets the local binding's value.
794 However, you should normally not make local bindings for variables
795 defined with this form.
797 The optional DOCSTRING specifies the variable's documentation string.
798 usage: (defconst SYMBOL INITVALUE [DOCSTRING]) */)
799 (Lisp_Object args)
801 Lisp_Object sym, tem;
803 sym = XCAR (args);
804 if (CONSP (Fcdr (XCDR (XCDR (args)))))
805 error ("Too many arguments");
807 tem = eval_sub (Fcar (XCDR (args)));
808 if (!NILP (Vpurify_flag))
809 tem = Fpurecopy (tem);
810 Fset_default (sym, tem);
811 XSYMBOL (sym)->declared_special = 1;
812 tem = Fcar (XCDR (XCDR (args)));
813 if (!NILP (tem))
815 if (!NILP (Vpurify_flag))
816 tem = Fpurecopy (tem);
817 Fput (sym, Qvariable_documentation, tem);
819 Fput (sym, Qrisky_local_variable, Qt);
820 LOADHIST_ATTACH (sym);
821 return sym;
824 /* Make SYMBOL lexically scoped. */
825 DEFUN ("internal-make-var-non-special", Fmake_var_non_special,
826 Smake_var_non_special, 1, 1, 0,
827 doc: /* Internal function. */)
828 (Lisp_Object symbol)
830 CHECK_SYMBOL (symbol);
831 XSYMBOL (symbol)->declared_special = 0;
832 return Qnil;
836 DEFUN ("let*", FletX, SletX, 1, UNEVALLED, 0,
837 doc: /* Bind variables according to VARLIST then eval BODY.
838 The value of the last form in BODY is returned.
839 Each element of VARLIST is a symbol (which is bound to nil)
840 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
841 Each VALUEFORM can refer to the symbols already bound by this VARLIST.
842 usage: (let* VARLIST BODY...) */)
843 (Lisp_Object args)
845 Lisp_Object varlist, var, val, elt, lexenv;
846 ptrdiff_t count = SPECPDL_INDEX ();
848 lexenv = Vinternal_interpreter_environment;
850 varlist = XCAR (args);
851 while (CONSP (varlist))
853 QUIT;
855 elt = XCAR (varlist);
856 if (SYMBOLP (elt))
858 var = elt;
859 val = Qnil;
861 else if (! NILP (Fcdr (Fcdr (elt))))
862 signal_error ("`let' bindings can have only one value-form", elt);
863 else
865 var = Fcar (elt);
866 val = eval_sub (Fcar (Fcdr (elt)));
869 if (!NILP (lexenv) && SYMBOLP (var)
870 && !XSYMBOL (var)->declared_special
871 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
872 /* Lexically bind VAR by adding it to the interpreter's binding
873 alist. */
875 Lisp_Object newenv
876 = Fcons (Fcons (var, val), Vinternal_interpreter_environment);
877 if (EQ (Vinternal_interpreter_environment, lexenv))
878 /* Save the old lexical environment on the specpdl stack,
879 but only for the first lexical binding, since we'll never
880 need to revert to one of the intermediate ones. */
881 specbind (Qinternal_interpreter_environment, newenv);
882 else
883 Vinternal_interpreter_environment = newenv;
885 else
886 specbind (var, val);
888 varlist = XCDR (varlist);
891 val = Fprogn (XCDR (args));
892 return unbind_to (count, val);
895 DEFUN ("let", Flet, Slet, 1, UNEVALLED, 0,
896 doc: /* Bind variables according to VARLIST then eval BODY.
897 The value of the last form in BODY is returned.
898 Each element of VARLIST is a symbol (which is bound to nil)
899 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
900 All the VALUEFORMs are evalled before any symbols are bound.
901 usage: (let VARLIST BODY...) */)
902 (Lisp_Object args)
904 Lisp_Object *temps, tem, lexenv;
905 Lisp_Object elt, varlist;
906 ptrdiff_t count = SPECPDL_INDEX ();
907 ptrdiff_t argnum;
908 USE_SAFE_ALLOCA;
910 varlist = XCAR (args);
912 /* Make space to hold the values to give the bound variables. */
913 elt = Flength (varlist);
914 SAFE_ALLOCA_LISP (temps, XFASTINT (elt));
916 /* Compute the values and store them in `temps'. */
918 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
920 QUIT;
921 elt = XCAR (varlist);
922 if (SYMBOLP (elt))
923 temps [argnum++] = Qnil;
924 else if (! NILP (Fcdr (Fcdr (elt))))
925 signal_error ("`let' bindings can have only one value-form", elt);
926 else
927 temps [argnum++] = eval_sub (Fcar (Fcdr (elt)));
930 lexenv = Vinternal_interpreter_environment;
932 varlist = XCAR (args);
933 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
935 Lisp_Object var;
937 elt = XCAR (varlist);
938 var = SYMBOLP (elt) ? elt : Fcar (elt);
939 tem = temps[argnum++];
941 if (!NILP (lexenv) && SYMBOLP (var)
942 && !XSYMBOL (var)->declared_special
943 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
944 /* Lexically bind VAR by adding it to the lexenv alist. */
945 lexenv = Fcons (Fcons (var, tem), lexenv);
946 else
947 /* Dynamically bind VAR. */
948 specbind (var, tem);
951 if (!EQ (lexenv, Vinternal_interpreter_environment))
952 /* Instantiate a new lexical environment. */
953 specbind (Qinternal_interpreter_environment, lexenv);
955 elt = Fprogn (XCDR (args));
956 SAFE_FREE ();
957 return unbind_to (count, elt);
960 DEFUN ("while", Fwhile, Swhile, 1, UNEVALLED, 0,
961 doc: /* If TEST yields non-nil, eval BODY... and repeat.
962 The order of execution is thus TEST, BODY, TEST, BODY and so on
963 until TEST returns nil.
964 usage: (while TEST BODY...) */)
965 (Lisp_Object args)
967 Lisp_Object test, body;
969 test = XCAR (args);
970 body = XCDR (args);
971 while (!NILP (eval_sub (test)))
973 QUIT;
974 Fprogn (body);
977 return Qnil;
980 DEFUN ("macroexpand", Fmacroexpand, Smacroexpand, 1, 2, 0,
981 doc: /* Return result of expanding macros at top level of FORM.
982 If FORM is not a macro call, it is returned unchanged.
983 Otherwise, the macro is expanded and the expansion is considered
984 in place of FORM. When a non-macro-call results, it is returned.
986 The second optional arg ENVIRONMENT specifies an environment of macro
987 definitions to shadow the loaded ones for use in file byte-compilation. */)
988 (Lisp_Object form, Lisp_Object environment)
990 /* With cleanups from Hallvard Furuseth. */
991 register Lisp_Object expander, sym, def, tem;
993 while (1)
995 /* Come back here each time we expand a macro call,
996 in case it expands into another macro call. */
997 if (!CONSP (form))
998 break;
999 /* Set SYM, give DEF and TEM right values in case SYM is not a symbol. */
1000 def = sym = XCAR (form);
1001 tem = Qnil;
1002 /* Trace symbols aliases to other symbols
1003 until we get a symbol that is not an alias. */
1004 while (SYMBOLP (def))
1006 QUIT;
1007 sym = def;
1008 tem = Fassq (sym, environment);
1009 if (NILP (tem))
1011 def = XSYMBOL (sym)->function;
1012 if (!NILP (def))
1013 continue;
1015 break;
1017 /* Right now TEM is the result from SYM in ENVIRONMENT,
1018 and if TEM is nil then DEF is SYM's function definition. */
1019 if (NILP (tem))
1021 /* SYM is not mentioned in ENVIRONMENT.
1022 Look at its function definition. */
1023 def = Fautoload_do_load (def, sym, Qmacro);
1024 if (!CONSP (def))
1025 /* Not defined or definition not suitable. */
1026 break;
1027 if (!EQ (XCAR (def), Qmacro))
1028 break;
1029 else expander = XCDR (def);
1031 else
1033 expander = XCDR (tem);
1034 if (NILP (expander))
1035 break;
1038 Lisp_Object newform = apply1 (expander, XCDR (form));
1039 if (EQ (form, newform))
1040 break;
1041 else
1042 form = newform;
1045 return form;
1048 DEFUN ("catch", Fcatch, Scatch, 1, UNEVALLED, 0,
1049 doc: /* Eval BODY allowing nonlocal exits using `throw'.
1050 TAG is evalled to get the tag to use; it must not be nil.
1052 Then the BODY is executed.
1053 Within BODY, a call to `throw' with the same TAG exits BODY and this `catch'.
1054 If no throw happens, `catch' returns the value of the last BODY form.
1055 If a throw happens, it specifies the value to return from `catch'.
1056 usage: (catch TAG BODY...) */)
1057 (Lisp_Object args)
1059 Lisp_Object tag = eval_sub (XCAR (args));
1060 return internal_catch (tag, Fprogn, XCDR (args));
1063 /* Assert that E is true, but do not evaluate E. Use this instead of
1064 eassert (E) when E contains variables that might be clobbered by a
1065 longjmp. */
1067 #define clobbered_eassert(E) verify (sizeof (E) != 0)
1069 /* Set up a catch, then call C function FUNC on argument ARG.
1070 FUNC should return a Lisp_Object.
1071 This is how catches are done from within C code. */
1073 Lisp_Object
1074 internal_catch (Lisp_Object tag,
1075 Lisp_Object (*func) (Lisp_Object), Lisp_Object arg)
1077 /* This structure is made part of the chain `catchlist'. */
1078 struct handler *c = push_handler (tag, CATCHER);
1080 /* Call FUNC. */
1081 if (! sys_setjmp (c->jmp))
1083 Lisp_Object val = func (arg);
1084 clobbered_eassert (handlerlist == c);
1085 handlerlist = handlerlist->next;
1086 return val;
1088 else
1089 { /* Throw works by a longjmp that comes right here. */
1090 Lisp_Object val = handlerlist->val;
1091 clobbered_eassert (handlerlist == c);
1092 handlerlist = handlerlist->next;
1093 return val;
1097 /* Unwind the specbind, catch, and handler stacks back to CATCH, and
1098 jump to that CATCH, returning VALUE as the value of that catch.
1100 This is the guts of Fthrow and Fsignal; they differ only in the way
1101 they choose the catch tag to throw to. A catch tag for a
1102 condition-case form has a TAG of Qnil.
1104 Before each catch is discarded, unbind all special bindings and
1105 execute all unwind-protect clauses made above that catch. Unwind
1106 the handler stack as we go, so that the proper handlers are in
1107 effect for each unwind-protect clause we run. At the end, restore
1108 some static info saved in CATCH, and longjmp to the location
1109 specified there.
1111 This is used for correct unwinding in Fthrow and Fsignal. */
1113 static _Noreturn void
1114 unwind_to_catch (struct handler *catch, Lisp_Object value)
1116 bool last_time;
1118 eassert (catch->next);
1120 /* Save the value in the tag. */
1121 catch->val = value;
1123 /* Restore certain special C variables. */
1124 set_poll_suppress_count (catch->poll_suppress_count);
1125 unblock_input_to (catch->interrupt_input_blocked);
1126 immediate_quit = 0;
1130 /* Unwind the specpdl stack, and then restore the proper set of
1131 handlers. */
1132 unbind_to (handlerlist->pdlcount, Qnil);
1133 last_time = handlerlist == catch;
1134 if (! last_time)
1135 handlerlist = handlerlist->next;
1137 while (! last_time);
1139 eassert (handlerlist == catch);
1141 lisp_eval_depth = catch->lisp_eval_depth;
1143 sys_longjmp (catch->jmp, 1);
1146 DEFUN ("throw", Fthrow, Sthrow, 2, 2, 0,
1147 doc: /* Throw to the catch for TAG and return VALUE from it.
1148 Both TAG and VALUE are evalled. */
1149 attributes: noreturn)
1150 (register Lisp_Object tag, Lisp_Object value)
1152 struct handler *c;
1154 if (!NILP (tag))
1155 for (c = handlerlist; c; c = c->next)
1157 if (c->type == CATCHER_ALL)
1158 unwind_to_catch (c, Fcons (tag, value));
1159 if (c->type == CATCHER && EQ (c->tag_or_ch, tag))
1160 unwind_to_catch (c, value);
1162 xsignal2 (Qno_catch, tag, value);
1166 DEFUN ("unwind-protect", Funwind_protect, Sunwind_protect, 1, UNEVALLED, 0,
1167 doc: /* Do BODYFORM, protecting with UNWINDFORMS.
1168 If BODYFORM completes normally, its value is returned
1169 after executing the UNWINDFORMS.
1170 If BODYFORM exits nonlocally, the UNWINDFORMS are executed anyway.
1171 usage: (unwind-protect BODYFORM UNWINDFORMS...) */)
1172 (Lisp_Object args)
1174 Lisp_Object val;
1175 ptrdiff_t count = SPECPDL_INDEX ();
1177 record_unwind_protect (unwind_body, XCDR (args));
1178 val = eval_sub (XCAR (args));
1179 return unbind_to (count, val);
1182 DEFUN ("condition-case", Fcondition_case, Scondition_case, 2, UNEVALLED, 0,
1183 doc: /* Regain control when an error is signaled.
1184 Executes BODYFORM and returns its value if no error happens.
1185 Each element of HANDLERS looks like (CONDITION-NAME BODY...)
1186 where the BODY is made of Lisp expressions.
1188 A handler is applicable to an error
1189 if CONDITION-NAME is one of the error's condition names.
1190 If an error happens, the first applicable handler is run.
1192 The car of a handler may be a list of condition names instead of a
1193 single condition name; then it handles all of them. If the special
1194 condition name `debug' is present in this list, it allows another
1195 condition in the list to run the debugger if `debug-on-error' and the
1196 other usual mechanisms says it should (otherwise, `condition-case'
1197 suppresses the debugger).
1199 When a handler handles an error, control returns to the `condition-case'
1200 and it executes the handler's BODY...
1201 with VAR bound to (ERROR-SYMBOL . SIGNAL-DATA) from the error.
1202 \(If VAR is nil, the handler can't access that information.)
1203 Then the value of the last BODY form is returned from the `condition-case'
1204 expression.
1206 See also the function `signal' for more info.
1207 usage: (condition-case VAR BODYFORM &rest HANDLERS) */)
1208 (Lisp_Object args)
1210 Lisp_Object var = XCAR (args);
1211 Lisp_Object bodyform = XCAR (XCDR (args));
1212 Lisp_Object handlers = XCDR (XCDR (args));
1214 return internal_lisp_condition_case (var, bodyform, handlers);
1217 /* Like Fcondition_case, but the args are separate
1218 rather than passed in a list. Used by Fbyte_code. */
1220 Lisp_Object
1221 internal_lisp_condition_case (volatile Lisp_Object var, Lisp_Object bodyform,
1222 Lisp_Object handlers)
1224 Lisp_Object val;
1225 struct handler *oldhandlerlist = handlerlist;
1226 int clausenb = 0;
1228 CHECK_SYMBOL (var);
1230 for (val = handlers; CONSP (val); val = XCDR (val))
1232 Lisp_Object tem = XCAR (val);
1233 clausenb++;
1234 if (! (NILP (tem)
1235 || (CONSP (tem)
1236 && (SYMBOLP (XCAR (tem))
1237 || CONSP (XCAR (tem))))))
1238 error ("Invalid condition handler: %s",
1239 SDATA (Fprin1_to_string (tem, Qt)));
1242 { /* The first clause is the one that should be checked first, so it should
1243 be added to handlerlist last. So we build in `clauses' a table that
1244 contains `handlers' but in reverse order. SAFE_ALLOCA won't work
1245 here due to the setjmp, so impose a MAX_ALLOCA limit. */
1246 if (MAX_ALLOCA / word_size < clausenb)
1247 memory_full (SIZE_MAX);
1248 Lisp_Object *clauses = alloca (clausenb * sizeof *clauses);
1249 Lisp_Object *volatile clauses_volatile = clauses;
1250 int i = clausenb;
1251 for (val = handlers; CONSP (val); val = XCDR (val))
1252 clauses[--i] = XCAR (val);
1253 for (i = 0; i < clausenb; i++)
1255 Lisp_Object clause = clauses[i];
1256 Lisp_Object condition = CONSP (clause) ? XCAR (clause) : Qnil;
1257 if (!CONSP (condition))
1258 condition = Fcons (condition, Qnil);
1259 struct handler *c = push_handler (condition, CONDITION_CASE);
1260 if (sys_setjmp (c->jmp))
1262 ptrdiff_t count = SPECPDL_INDEX ();
1263 Lisp_Object val = handlerlist->val;
1264 Lisp_Object *chosen_clause = clauses_volatile;
1265 for (c = handlerlist->next; c != oldhandlerlist; c = c->next)
1266 chosen_clause++;
1267 handlerlist = oldhandlerlist;
1268 if (!NILP (var))
1270 if (!NILP (Vinternal_interpreter_environment))
1271 specbind (Qinternal_interpreter_environment,
1272 Fcons (Fcons (var, val),
1273 Vinternal_interpreter_environment));
1274 else
1275 specbind (var, val);
1277 val = Fprogn (XCDR (*chosen_clause));
1278 /* Note that this just undoes the binding of var; whoever
1279 longjumped to us unwound the stack to c.pdlcount before
1280 throwing. */
1281 if (!NILP (var))
1282 unbind_to (count, Qnil);
1283 return val;
1288 val = eval_sub (bodyform);
1289 handlerlist = oldhandlerlist;
1290 return val;
1293 /* Call the function BFUN with no arguments, catching errors within it
1294 according to HANDLERS. If there is an error, call HFUN with
1295 one argument which is the data that describes the error:
1296 (SIGNALNAME . DATA)
1298 HANDLERS can be a list of conditions to catch.
1299 If HANDLERS is Qt, catch all errors.
1300 If HANDLERS is Qerror, catch all errors
1301 but allow the debugger to run if that is enabled. */
1303 Lisp_Object
1304 internal_condition_case (Lisp_Object (*bfun) (void), Lisp_Object handlers,
1305 Lisp_Object (*hfun) (Lisp_Object))
1307 struct handler *c = push_handler (handlers, CONDITION_CASE);
1308 if (sys_setjmp (c->jmp))
1310 Lisp_Object val = handlerlist->val;
1311 clobbered_eassert (handlerlist == c);
1312 handlerlist = handlerlist->next;
1313 return hfun (val);
1315 else
1317 Lisp_Object val = bfun ();
1318 clobbered_eassert (handlerlist == c);
1319 handlerlist = handlerlist->next;
1320 return val;
1324 /* Like internal_condition_case but call BFUN with ARG as its argument. */
1326 Lisp_Object
1327 internal_condition_case_1 (Lisp_Object (*bfun) (Lisp_Object), Lisp_Object arg,
1328 Lisp_Object handlers,
1329 Lisp_Object (*hfun) (Lisp_Object))
1331 struct handler *c = push_handler (handlers, CONDITION_CASE);
1332 if (sys_setjmp (c->jmp))
1334 Lisp_Object val = handlerlist->val;
1335 clobbered_eassert (handlerlist == c);
1336 handlerlist = handlerlist->next;
1337 return hfun (val);
1339 else
1341 Lisp_Object val = bfun (arg);
1342 clobbered_eassert (handlerlist == c);
1343 handlerlist = handlerlist->next;
1344 return val;
1348 /* Like internal_condition_case_1 but call BFUN with ARG1 and ARG2 as
1349 its arguments. */
1351 Lisp_Object
1352 internal_condition_case_2 (Lisp_Object (*bfun) (Lisp_Object, Lisp_Object),
1353 Lisp_Object arg1,
1354 Lisp_Object arg2,
1355 Lisp_Object handlers,
1356 Lisp_Object (*hfun) (Lisp_Object))
1358 struct handler *c = push_handler (handlers, CONDITION_CASE);
1359 if (sys_setjmp (c->jmp))
1361 Lisp_Object val = handlerlist->val;
1362 clobbered_eassert (handlerlist == c);
1363 handlerlist = handlerlist->next;
1364 return hfun (val);
1366 else
1368 Lisp_Object val = bfun (arg1, arg2);
1369 clobbered_eassert (handlerlist == c);
1370 handlerlist = handlerlist->next;
1371 return val;
1375 /* Like internal_condition_case but call BFUN with NARGS as first,
1376 and ARGS as second argument. */
1378 Lisp_Object
1379 internal_condition_case_n (Lisp_Object (*bfun) (ptrdiff_t, Lisp_Object *),
1380 ptrdiff_t nargs,
1381 Lisp_Object *args,
1382 Lisp_Object handlers,
1383 Lisp_Object (*hfun) (Lisp_Object err,
1384 ptrdiff_t nargs,
1385 Lisp_Object *args))
1387 struct handler *c = push_handler (handlers, CONDITION_CASE);
1388 if (sys_setjmp (c->jmp))
1390 Lisp_Object val = handlerlist->val;
1391 clobbered_eassert (handlerlist == c);
1392 handlerlist = handlerlist->next;
1393 return hfun (val, nargs, args);
1395 else
1397 Lisp_Object val = bfun (nargs, args);
1398 clobbered_eassert (handlerlist == c);
1399 handlerlist = handlerlist->next;
1400 return val;
1404 struct handler *
1405 push_handler (Lisp_Object tag_ch_val, enum handlertype handlertype)
1407 struct handler *c = push_handler_nosignal (tag_ch_val, handlertype);
1408 if (!c)
1409 memory_full (sizeof *c);
1410 return c;
1413 struct handler *
1414 push_handler_nosignal (Lisp_Object tag_ch_val, enum handlertype handlertype)
1416 struct handler *c = handlerlist->nextfree;
1417 if (!c)
1419 c = malloc (sizeof *c);
1420 if (!c)
1421 return c;
1422 if (profiler_memory_running)
1423 malloc_probe (sizeof *c);
1424 c->nextfree = NULL;
1425 handlerlist->nextfree = c;
1427 c->type = handlertype;
1428 c->tag_or_ch = tag_ch_val;
1429 c->val = Qnil;
1430 c->next = handlerlist;
1431 c->lisp_eval_depth = lisp_eval_depth;
1432 c->pdlcount = SPECPDL_INDEX ();
1433 c->poll_suppress_count = poll_suppress_count;
1434 c->interrupt_input_blocked = interrupt_input_blocked;
1435 handlerlist = c;
1436 return c;
1440 static Lisp_Object signal_or_quit (Lisp_Object, Lisp_Object, bool);
1441 static Lisp_Object find_handler_clause (Lisp_Object, Lisp_Object);
1442 static bool maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig,
1443 Lisp_Object data);
1445 void
1446 process_quit_flag (void)
1448 Lisp_Object flag = Vquit_flag;
1449 Vquit_flag = Qnil;
1450 if (EQ (flag, Qkill_emacs))
1451 Fkill_emacs (Qnil);
1452 if (EQ (Vthrow_on_input, flag))
1453 Fthrow (Vthrow_on_input, Qt);
1454 quit ();
1457 DEFUN ("signal", Fsignal, Ssignal, 2, 2, 0,
1458 doc: /* Signal an error. Args are ERROR-SYMBOL and associated DATA.
1459 This function does not return.
1461 An error symbol is a symbol with an `error-conditions' property
1462 that is a list of condition names.
1463 A handler for any of those names will get to handle this signal.
1464 The symbol `error' should normally be one of them.
1466 DATA should be a list. Its elements are printed as part of the error message.
1467 See Info anchor `(elisp)Definition of signal' for some details on how this
1468 error message is constructed.
1469 If the signal is handled, DATA is made available to the handler.
1470 See also the function `condition-case'. */
1471 attributes: noreturn)
1472 (Lisp_Object error_symbol, Lisp_Object data)
1474 signal_or_quit (error_symbol, data, false);
1475 eassume (false);
1478 /* Quit, in response to a keyboard quit request. */
1479 Lisp_Object
1480 quit (void)
1482 return signal_or_quit (Qquit, Qnil, true);
1485 /* Signal an error, or quit. ERROR_SYMBOL and DATA are as with Fsignal.
1486 If KEYBOARD_QUIT, this is a quit; ERROR_SYMBOL should be
1487 Qquit and DATA should be Qnil, and this function may return.
1488 Otherwise this function is like Fsignal and does not return. */
1490 static Lisp_Object
1491 signal_or_quit (Lisp_Object error_symbol, Lisp_Object data, bool keyboard_quit)
1493 /* When memory is full, ERROR-SYMBOL is nil,
1494 and DATA is (REAL-ERROR-SYMBOL . REAL-DATA).
1495 That is a special case--don't do this in other situations. */
1496 Lisp_Object conditions;
1497 Lisp_Object string;
1498 Lisp_Object real_error_symbol
1499 = (NILP (error_symbol) ? Fcar (data) : error_symbol);
1500 register Lisp_Object clause = Qnil;
1501 struct handler *h;
1503 immediate_quit = 0;
1504 if (gc_in_progress || waiting_for_input)
1505 emacs_abort ();
1507 #if 0 /* rms: I don't know why this was here,
1508 but it is surely wrong for an error that is handled. */
1509 #ifdef HAVE_WINDOW_SYSTEM
1510 if (display_hourglass_p)
1511 cancel_hourglass ();
1512 #endif
1513 #endif
1515 /* This hook is used by edebug. */
1516 if (! NILP (Vsignal_hook_function)
1517 && ! NILP (error_symbol))
1519 /* Edebug takes care of restoring these variables when it exits. */
1520 if (lisp_eval_depth + 20 > max_lisp_eval_depth)
1521 max_lisp_eval_depth = lisp_eval_depth + 20;
1523 if (SPECPDL_INDEX () + 40 > max_specpdl_size)
1524 max_specpdl_size = SPECPDL_INDEX () + 40;
1526 call2 (Vsignal_hook_function, error_symbol, data);
1529 conditions = Fget (real_error_symbol, Qerror_conditions);
1531 /* Remember from where signal was called. Skip over the frame for
1532 `signal' itself. If a frame for `error' follows, skip that,
1533 too. Don't do this when ERROR_SYMBOL is nil, because that
1534 is a memory-full error. */
1535 Vsignaling_function = Qnil;
1536 if (!NILP (error_symbol))
1538 union specbinding *pdl = backtrace_next (backtrace_top ());
1539 if (backtrace_p (pdl) && EQ (backtrace_function (pdl), Qerror))
1540 pdl = backtrace_next (pdl);
1541 if (backtrace_p (pdl))
1542 Vsignaling_function = backtrace_function (pdl);
1545 for (h = handlerlist; h; h = h->next)
1547 if (h->type != CONDITION_CASE)
1548 continue;
1549 clause = find_handler_clause (h->tag_or_ch, conditions);
1550 if (!NILP (clause))
1551 break;
1554 if (/* Don't run the debugger for a memory-full error.
1555 (There is no room in memory to do that!) */
1556 !NILP (error_symbol)
1557 && (!NILP (Vdebug_on_signal)
1558 /* If no handler is present now, try to run the debugger. */
1559 || NILP (clause)
1560 /* A `debug' symbol in the handler list disables the normal
1561 suppression of the debugger. */
1562 || (CONSP (clause) && !NILP (Fmemq (Qdebug, clause)))
1563 /* Special handler that means "print a message and run debugger
1564 if requested". */
1565 || EQ (h->tag_or_ch, Qerror)))
1567 bool debugger_called
1568 = maybe_call_debugger (conditions, error_symbol, data);
1569 /* We can't return values to code which signaled an error, but we
1570 can continue code which has signaled a quit. */
1571 if (keyboard_quit && debugger_called && EQ (real_error_symbol, Qquit))
1572 return Qnil;
1575 if (!NILP (clause))
1577 Lisp_Object unwind_data
1578 = (NILP (error_symbol) ? data : Fcons (error_symbol, data));
1580 unwind_to_catch (h, unwind_data);
1582 else
1584 if (handlerlist != &handlerlist_sentinel)
1585 /* FIXME: This will come right back here if there's no `top-level'
1586 catcher. A better solution would be to abort here, and instead
1587 add a catch-all condition handler so we never come here. */
1588 Fthrow (Qtop_level, Qt);
1591 if (! NILP (error_symbol))
1592 data = Fcons (error_symbol, data);
1594 string = Ferror_message_string (data);
1595 fatal ("%s", SDATA (string));
1598 /* Like xsignal, but takes 0, 1, 2, or 3 args instead of a list. */
1600 void
1601 xsignal0 (Lisp_Object error_symbol)
1603 xsignal (error_symbol, Qnil);
1606 void
1607 xsignal1 (Lisp_Object error_symbol, Lisp_Object arg)
1609 xsignal (error_symbol, list1 (arg));
1612 void
1613 xsignal2 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2)
1615 xsignal (error_symbol, list2 (arg1, arg2));
1618 void
1619 xsignal3 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
1621 xsignal (error_symbol, list3 (arg1, arg2, arg3));
1624 /* Signal `error' with message S, and additional arg ARG.
1625 If ARG is not a genuine list, make it a one-element list. */
1627 void
1628 signal_error (const char *s, Lisp_Object arg)
1630 Lisp_Object tortoise, hare;
1632 hare = tortoise = arg;
1633 while (CONSP (hare))
1635 hare = XCDR (hare);
1636 if (!CONSP (hare))
1637 break;
1639 hare = XCDR (hare);
1640 tortoise = XCDR (tortoise);
1642 if (EQ (hare, tortoise))
1643 break;
1646 if (!NILP (hare))
1647 arg = list1 (arg);
1649 xsignal (Qerror, Fcons (build_string (s), arg));
1653 /* Return true if LIST is a non-nil atom or
1654 a list containing one of CONDITIONS. */
1656 static bool
1657 wants_debugger (Lisp_Object list, Lisp_Object conditions)
1659 if (NILP (list))
1660 return 0;
1661 if (! CONSP (list))
1662 return 1;
1664 while (CONSP (conditions))
1666 Lisp_Object this, tail;
1667 this = XCAR (conditions);
1668 for (tail = list; CONSP (tail); tail = XCDR (tail))
1669 if (EQ (XCAR (tail), this))
1670 return 1;
1671 conditions = XCDR (conditions);
1673 return 0;
1676 /* Return true if an error with condition-symbols CONDITIONS,
1677 and described by SIGNAL-DATA, should skip the debugger
1678 according to debugger-ignored-errors. */
1680 static bool
1681 skip_debugger (Lisp_Object conditions, Lisp_Object data)
1683 Lisp_Object tail;
1684 bool first_string = 1;
1685 Lisp_Object error_message;
1687 error_message = Qnil;
1688 for (tail = Vdebug_ignored_errors; CONSP (tail); tail = XCDR (tail))
1690 if (STRINGP (XCAR (tail)))
1692 if (first_string)
1694 error_message = Ferror_message_string (data);
1695 first_string = 0;
1698 if (fast_string_match (XCAR (tail), error_message) >= 0)
1699 return 1;
1701 else
1703 Lisp_Object contail;
1705 for (contail = conditions; CONSP (contail); contail = XCDR (contail))
1706 if (EQ (XCAR (tail), XCAR (contail)))
1707 return 1;
1711 return 0;
1714 /* Call the debugger if calling it is currently enabled for CONDITIONS.
1715 SIG and DATA describe the signal. There are two ways to pass them:
1716 = SIG is the error symbol, and DATA is the rest of the data.
1717 = SIG is nil, and DATA is (SYMBOL . REST-OF-DATA).
1718 This is for memory-full errors only. */
1719 static bool
1720 maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig, Lisp_Object data)
1722 Lisp_Object combined_data;
1724 combined_data = Fcons (sig, data);
1726 if (
1727 /* Don't try to run the debugger with interrupts blocked.
1728 The editing loop would return anyway. */
1729 ! input_blocked_p ()
1730 && NILP (Vinhibit_debugger)
1731 /* Does user want to enter debugger for this kind of error? */
1732 && (EQ (sig, Qquit)
1733 ? debug_on_quit
1734 : wants_debugger (Vdebug_on_error, conditions))
1735 && ! skip_debugger (conditions, combined_data)
1736 /* RMS: What's this for? */
1737 && when_entered_debugger < num_nonmacro_input_events)
1739 call_debugger (list2 (Qerror, combined_data));
1740 return 1;
1743 return 0;
1746 static Lisp_Object
1747 find_handler_clause (Lisp_Object handlers, Lisp_Object conditions)
1749 register Lisp_Object h;
1751 /* t is used by handlers for all conditions, set up by C code. */
1752 if (EQ (handlers, Qt))
1753 return Qt;
1755 /* error is used similarly, but means print an error message
1756 and run the debugger if that is enabled. */
1757 if (EQ (handlers, Qerror))
1758 return Qt;
1760 for (h = handlers; CONSP (h); h = XCDR (h))
1762 Lisp_Object handler = XCAR (h);
1763 if (!NILP (Fmemq (handler, conditions)))
1764 return handlers;
1767 return Qnil;
1771 /* Format and return a string; called like vprintf. */
1772 Lisp_Object
1773 vformat_string (const char *m, va_list ap)
1775 char buf[4000];
1776 ptrdiff_t size = sizeof buf;
1777 ptrdiff_t size_max = STRING_BYTES_BOUND + 1;
1778 char *buffer = buf;
1779 ptrdiff_t used;
1780 Lisp_Object string;
1782 used = evxprintf (&buffer, &size, buf, size_max, m, ap);
1783 string = make_string (buffer, used);
1784 if (buffer != buf)
1785 xfree (buffer);
1787 return string;
1790 /* Dump an error message; called like vprintf. */
1791 void
1792 verror (const char *m, va_list ap)
1794 xsignal1 (Qerror, vformat_string (m, ap));
1798 /* Dump an error message; called like printf. */
1800 /* VARARGS 1 */
1801 void
1802 error (const char *m, ...)
1804 va_list ap;
1805 va_start (ap, m);
1806 verror (m, ap);
1809 DEFUN ("commandp", Fcommandp, Scommandp, 1, 2, 0,
1810 doc: /* Non-nil if FUNCTION makes provisions for interactive calling.
1811 This means it contains a description for how to read arguments to give it.
1812 The value is nil for an invalid function or a symbol with no function
1813 definition.
1815 Interactively callable functions include strings and vectors (treated
1816 as keyboard macros), lambda-expressions that contain a top-level call
1817 to `interactive', autoload definitions made by `autoload' with non-nil
1818 fourth argument, and some of the built-in functions of Lisp.
1820 Also, a symbol satisfies `commandp' if its function definition does so.
1822 If the optional argument FOR-CALL-INTERACTIVELY is non-nil,
1823 then strings and vectors are not accepted. */)
1824 (Lisp_Object function, Lisp_Object for_call_interactively)
1826 register Lisp_Object fun;
1827 register Lisp_Object funcar;
1828 Lisp_Object if_prop = Qnil;
1830 fun = function;
1832 fun = indirect_function (fun); /* Check cycles. */
1833 if (NILP (fun))
1834 return Qnil;
1836 /* Check an `interactive-form' property if present, analogous to the
1837 function-documentation property. */
1838 fun = function;
1839 while (SYMBOLP (fun))
1841 Lisp_Object tmp = Fget (fun, Qinteractive_form);
1842 if (!NILP (tmp))
1843 if_prop = Qt;
1844 fun = Fsymbol_function (fun);
1847 /* Emacs primitives are interactive if their DEFUN specifies an
1848 interactive spec. */
1849 if (SUBRP (fun))
1850 return XSUBR (fun)->intspec ? Qt : if_prop;
1852 /* Bytecode objects are interactive if they are long enough to
1853 have an element whose index is COMPILED_INTERACTIVE, which is
1854 where the interactive spec is stored. */
1855 else if (COMPILEDP (fun))
1856 return ((ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK) > COMPILED_INTERACTIVE
1857 ? Qt : if_prop);
1859 /* Strings and vectors are keyboard macros. */
1860 if (STRINGP (fun) || VECTORP (fun))
1861 return (NILP (for_call_interactively) ? Qt : Qnil);
1863 /* Lists may represent commands. */
1864 if (!CONSP (fun))
1865 return Qnil;
1866 funcar = XCAR (fun);
1867 if (EQ (funcar, Qclosure))
1868 return (!NILP (Fassq (Qinteractive, Fcdr (Fcdr (XCDR (fun)))))
1869 ? Qt : if_prop);
1870 else if (EQ (funcar, Qlambda))
1871 return !NILP (Fassq (Qinteractive, Fcdr (XCDR (fun)))) ? Qt : if_prop;
1872 else if (EQ (funcar, Qautoload))
1873 return !NILP (Fcar (Fcdr (Fcdr (XCDR (fun))))) ? Qt : if_prop;
1874 else
1875 return Qnil;
1878 DEFUN ("autoload", Fautoload, Sautoload, 2, 5, 0,
1879 doc: /* Define FUNCTION to autoload from FILE.
1880 FUNCTION is a symbol; FILE is a file name string to pass to `load'.
1881 Third arg DOCSTRING is documentation for the function.
1882 Fourth arg INTERACTIVE if non-nil says function can be called interactively.
1883 Fifth arg TYPE indicates the type of the object:
1884 nil or omitted says FUNCTION is a function,
1885 `keymap' says FUNCTION is really a keymap, and
1886 `macro' or t says FUNCTION is really a macro.
1887 Third through fifth args give info about the real definition.
1888 They default to nil.
1889 If FUNCTION is already defined other than as an autoload,
1890 this does nothing and returns nil. */)
1891 (Lisp_Object function, Lisp_Object file, Lisp_Object docstring, Lisp_Object interactive, Lisp_Object type)
1893 CHECK_SYMBOL (function);
1894 CHECK_STRING (file);
1896 /* If function is defined and not as an autoload, don't override. */
1897 if (!NILP (XSYMBOL (function)->function)
1898 && !AUTOLOADP (XSYMBOL (function)->function))
1899 return Qnil;
1901 if (!NILP (Vpurify_flag) && EQ (docstring, make_number (0)))
1902 /* `read1' in lread.c has found the docstring starting with "\
1903 and assumed the docstring will be provided by Snarf-documentation, so it
1904 passed us 0 instead. But that leads to accidental sharing in purecopy's
1905 hash-consing, so we use a (hopefully) unique integer instead. */
1906 docstring = make_number (XHASH (function));
1907 return Fdefalias (function,
1908 list5 (Qautoload, file, docstring, interactive, type),
1909 Qnil);
1912 void
1913 un_autoload (Lisp_Object oldqueue)
1915 Lisp_Object queue, first, second;
1917 /* Queue to unwind is current value of Vautoload_queue.
1918 oldqueue is the shadowed value to leave in Vautoload_queue. */
1919 queue = Vautoload_queue;
1920 Vautoload_queue = oldqueue;
1921 while (CONSP (queue))
1923 first = XCAR (queue);
1924 second = Fcdr (first);
1925 first = Fcar (first);
1926 if (EQ (first, make_number (0)))
1927 Vfeatures = second;
1928 else
1929 Ffset (first, second);
1930 queue = XCDR (queue);
1934 /* Load an autoloaded function.
1935 FUNNAME is the symbol which is the function's name.
1936 FUNDEF is the autoload definition (a list). */
1938 DEFUN ("autoload-do-load", Fautoload_do_load, Sautoload_do_load, 1, 3, 0,
1939 doc: /* Load FUNDEF which should be an autoload.
1940 If non-nil, FUNNAME should be the symbol whose function value is FUNDEF,
1941 in which case the function returns the new autoloaded function value.
1942 If equal to `macro', MACRO-ONLY specifies that FUNDEF should only be loaded if
1943 it defines a macro. */)
1944 (Lisp_Object fundef, Lisp_Object funname, Lisp_Object macro_only)
1946 ptrdiff_t count = SPECPDL_INDEX ();
1948 if (!CONSP (fundef) || !EQ (Qautoload, XCAR (fundef)))
1949 return fundef;
1951 if (EQ (macro_only, Qmacro))
1953 Lisp_Object kind = Fnth (make_number (4), fundef);
1954 if (! (EQ (kind, Qt) || EQ (kind, Qmacro)))
1955 return fundef;
1958 /* This is to make sure that loadup.el gives a clear picture
1959 of what files are preloaded and when. */
1960 if (! NILP (Vpurify_flag))
1961 error ("Attempt to autoload %s while preparing to dump",
1962 SDATA (SYMBOL_NAME (funname)));
1964 CHECK_SYMBOL (funname);
1966 /* Preserve the match data. */
1967 record_unwind_save_match_data ();
1969 /* If autoloading gets an error (which includes the error of failing
1970 to define the function being called), we use Vautoload_queue
1971 to undo function definitions and `provide' calls made by
1972 the function. We do this in the specific case of autoloading
1973 because autoloading is not an explicit request "load this file",
1974 but rather a request to "call this function".
1976 The value saved here is to be restored into Vautoload_queue. */
1977 record_unwind_protect (un_autoload, Vautoload_queue);
1978 Vautoload_queue = Qt;
1979 /* If `macro_only', assume this autoload to be a "best-effort",
1980 so don't signal an error if autoloading fails. */
1981 Fload (Fcar (Fcdr (fundef)), macro_only, Qt, Qnil, Qt);
1983 /* Once loading finishes, don't undo it. */
1984 Vautoload_queue = Qt;
1985 unbind_to (count, Qnil);
1987 if (NILP (funname))
1988 return Qnil;
1989 else
1991 Lisp_Object fun = Findirect_function (funname, Qnil);
1993 if (!NILP (Fequal (fun, fundef)))
1994 error ("Autoloading file %s failed to define function %s",
1995 SDATA (Fcar (Fcar (Vload_history))),
1996 SDATA (SYMBOL_NAME (funname)));
1997 else
1998 return fun;
2003 DEFUN ("eval", Feval, Seval, 1, 2, 0,
2004 doc: /* Evaluate FORM and return its value.
2005 If LEXICAL is t, evaluate using lexical scoping.
2006 LEXICAL can also be an actual lexical environment, in the form of an
2007 alist mapping symbols to their value. */)
2008 (Lisp_Object form, Lisp_Object lexical)
2010 ptrdiff_t count = SPECPDL_INDEX ();
2011 specbind (Qinternal_interpreter_environment,
2012 CONSP (lexical) || NILP (lexical) ? lexical : list1 (Qt));
2013 return unbind_to (count, eval_sub (form));
2016 /* Grow the specpdl stack by one entry.
2017 The caller should have already initialized the entry.
2018 Signal an error on stack overflow.
2020 Make sure that there is always one unused entry past the top of the
2021 stack, so that the just-initialized entry is safely unwound if
2022 memory exhausted and an error is signaled here. Also, allocate a
2023 never-used entry just before the bottom of the stack; sometimes its
2024 address is taken. */
2026 static void
2027 grow_specpdl (void)
2029 specpdl_ptr++;
2031 if (specpdl_ptr == specpdl + specpdl_size)
2033 ptrdiff_t count = SPECPDL_INDEX ();
2034 ptrdiff_t max_size = min (max_specpdl_size, PTRDIFF_MAX - 1000);
2035 union specbinding *pdlvec = specpdl - 1;
2036 ptrdiff_t pdlvecsize = specpdl_size + 1;
2037 if (max_size <= specpdl_size)
2039 if (max_specpdl_size < 400)
2040 max_size = max_specpdl_size = 400;
2041 if (max_size <= specpdl_size)
2042 signal_error ("Variable binding depth exceeds max-specpdl-size",
2043 Qnil);
2045 pdlvec = xpalloc (pdlvec, &pdlvecsize, 1, max_size + 1, sizeof *specpdl);
2046 specpdl = pdlvec + 1;
2047 specpdl_size = pdlvecsize - 1;
2048 specpdl_ptr = specpdl + count;
2052 ptrdiff_t
2053 record_in_backtrace (Lisp_Object function, Lisp_Object *args, ptrdiff_t nargs)
2055 ptrdiff_t count = SPECPDL_INDEX ();
2057 eassert (nargs >= UNEVALLED);
2058 specpdl_ptr->bt.kind = SPECPDL_BACKTRACE;
2059 specpdl_ptr->bt.debug_on_exit = false;
2060 specpdl_ptr->bt.function = function;
2061 specpdl_ptr->bt.args = args;
2062 specpdl_ptr->bt.nargs = nargs;
2063 grow_specpdl ();
2065 return count;
2068 /* Eval a sub-expression of the current expression (i.e. in the same
2069 lexical scope). */
2070 Lisp_Object
2071 eval_sub (Lisp_Object form)
2073 Lisp_Object fun, val, original_fun, original_args;
2074 Lisp_Object funcar;
2075 ptrdiff_t count;
2077 /* Declare here, as this array may be accessed by call_debugger near
2078 the end of this function. See Bug#21245. */
2079 Lisp_Object argvals[8];
2081 if (SYMBOLP (form))
2083 /* Look up its binding in the lexical environment.
2084 We do not pay attention to the declared_special flag here, since we
2085 already did that when let-binding the variable. */
2086 Lisp_Object lex_binding
2087 = !NILP (Vinternal_interpreter_environment) /* Mere optimization! */
2088 ? Fassq (form, Vinternal_interpreter_environment)
2089 : Qnil;
2090 if (CONSP (lex_binding))
2091 return XCDR (lex_binding);
2092 else
2093 return Fsymbol_value (form);
2096 if (!CONSP (form))
2097 return form;
2099 QUIT;
2101 maybe_gc ();
2103 if (++lisp_eval_depth > max_lisp_eval_depth)
2105 if (max_lisp_eval_depth < 100)
2106 max_lisp_eval_depth = 100;
2107 if (lisp_eval_depth > max_lisp_eval_depth)
2108 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2111 original_fun = XCAR (form);
2112 original_args = XCDR (form);
2114 /* This also protects them from gc. */
2115 count = record_in_backtrace (original_fun, &original_args, UNEVALLED);
2117 if (debug_on_next_call)
2118 do_debug_on_call (Qt, count);
2120 /* At this point, only original_fun and original_args
2121 have values that will be used below. */
2122 retry:
2124 /* Optimize for no indirection. */
2125 fun = original_fun;
2126 if (!SYMBOLP (fun))
2127 fun = Ffunction (Fcons (fun, Qnil));
2128 else if (!NILP (fun) && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2129 fun = indirect_function (fun);
2131 if (SUBRP (fun))
2133 Lisp_Object args_left = original_args;
2134 Lisp_Object numargs = Flength (args_left);
2136 check_cons_list ();
2138 if (XINT (numargs) < XSUBR (fun)->min_args
2139 || (XSUBR (fun)->max_args >= 0
2140 && XSUBR (fun)->max_args < XINT (numargs)))
2141 xsignal2 (Qwrong_number_of_arguments, original_fun, numargs);
2143 else if (XSUBR (fun)->max_args == UNEVALLED)
2144 val = (XSUBR (fun)->function.aUNEVALLED) (args_left);
2145 else if (XSUBR (fun)->max_args == MANY)
2147 /* Pass a vector of evaluated arguments. */
2148 Lisp_Object *vals;
2149 ptrdiff_t argnum = 0;
2150 USE_SAFE_ALLOCA;
2152 SAFE_ALLOCA_LISP (vals, XINT (numargs));
2154 while (!NILP (args_left))
2156 vals[argnum++] = eval_sub (Fcar (args_left));
2157 args_left = Fcdr (args_left);
2160 set_backtrace_args (specpdl + count, vals, XINT (numargs));
2162 val = (XSUBR (fun)->function.aMANY) (XINT (numargs), vals);
2164 check_cons_list ();
2165 lisp_eval_depth--;
2166 /* Do the debug-on-exit now, while VALS still exists. */
2167 if (backtrace_debug_on_exit (specpdl + count))
2168 val = call_debugger (list2 (Qexit, val));
2169 SAFE_FREE ();
2170 specpdl_ptr--;
2171 return val;
2173 else
2175 int i, maxargs = XSUBR (fun)->max_args;
2177 for (i = 0; i < maxargs; i++)
2179 argvals[i] = eval_sub (Fcar (args_left));
2180 args_left = Fcdr (args_left);
2183 set_backtrace_args (specpdl + count, argvals, XINT (numargs));
2185 switch (i)
2187 case 0:
2188 val = (XSUBR (fun)->function.a0 ());
2189 break;
2190 case 1:
2191 val = (XSUBR (fun)->function.a1 (argvals[0]));
2192 break;
2193 case 2:
2194 val = (XSUBR (fun)->function.a2 (argvals[0], argvals[1]));
2195 break;
2196 case 3:
2197 val = (XSUBR (fun)->function.a3
2198 (argvals[0], argvals[1], argvals[2]));
2199 break;
2200 case 4:
2201 val = (XSUBR (fun)->function.a4
2202 (argvals[0], argvals[1], argvals[2], argvals[3]));
2203 break;
2204 case 5:
2205 val = (XSUBR (fun)->function.a5
2206 (argvals[0], argvals[1], argvals[2], argvals[3],
2207 argvals[4]));
2208 break;
2209 case 6:
2210 val = (XSUBR (fun)->function.a6
2211 (argvals[0], argvals[1], argvals[2], argvals[3],
2212 argvals[4], argvals[5]));
2213 break;
2214 case 7:
2215 val = (XSUBR (fun)->function.a7
2216 (argvals[0], argvals[1], argvals[2], argvals[3],
2217 argvals[4], argvals[5], argvals[6]));
2218 break;
2220 case 8:
2221 val = (XSUBR (fun)->function.a8
2222 (argvals[0], argvals[1], argvals[2], argvals[3],
2223 argvals[4], argvals[5], argvals[6], argvals[7]));
2224 break;
2226 default:
2227 /* Someone has created a subr that takes more arguments than
2228 is supported by this code. We need to either rewrite the
2229 subr to use a different argument protocol, or add more
2230 cases to this switch. */
2231 emacs_abort ();
2235 else if (COMPILEDP (fun))
2236 return apply_lambda (fun, original_args, count);
2237 else
2239 if (NILP (fun))
2240 xsignal1 (Qvoid_function, original_fun);
2241 if (!CONSP (fun))
2242 xsignal1 (Qinvalid_function, original_fun);
2243 funcar = XCAR (fun);
2244 if (!SYMBOLP (funcar))
2245 xsignal1 (Qinvalid_function, original_fun);
2246 if (EQ (funcar, Qautoload))
2248 Fautoload_do_load (fun, original_fun, Qnil);
2249 goto retry;
2251 if (EQ (funcar, Qmacro))
2253 ptrdiff_t count1 = SPECPDL_INDEX ();
2254 Lisp_Object exp;
2255 /* Bind lexical-binding during expansion of the macro, so the
2256 macro can know reliably if the code it outputs will be
2257 interpreted using lexical-binding or not. */
2258 specbind (Qlexical_binding,
2259 NILP (Vinternal_interpreter_environment) ? Qnil : Qt);
2260 exp = apply1 (Fcdr (fun), original_args);
2261 unbind_to (count1, Qnil);
2262 val = eval_sub (exp);
2264 else if (EQ (funcar, Qlambda)
2265 || EQ (funcar, Qclosure))
2266 return apply_lambda (fun, original_args, count);
2267 else
2268 xsignal1 (Qinvalid_function, original_fun);
2270 check_cons_list ();
2272 lisp_eval_depth--;
2273 if (backtrace_debug_on_exit (specpdl + count))
2274 val = call_debugger (list2 (Qexit, val));
2275 specpdl_ptr--;
2277 return val;
2280 DEFUN ("apply", Fapply, Sapply, 1, MANY, 0,
2281 doc: /* Call FUNCTION with our remaining args, using our last arg as list of args.
2282 Then return the value FUNCTION returns.
2283 Thus, (apply \\='+ 1 2 \\='(3 4)) returns 10.
2284 usage: (apply FUNCTION &rest ARGUMENTS) */)
2285 (ptrdiff_t nargs, Lisp_Object *args)
2287 ptrdiff_t i, numargs, funcall_nargs;
2288 register Lisp_Object *funcall_args = NULL;
2289 register Lisp_Object spread_arg = args[nargs - 1];
2290 Lisp_Object fun = args[0];
2291 Lisp_Object retval;
2292 USE_SAFE_ALLOCA;
2294 CHECK_LIST (spread_arg);
2296 numargs = XINT (Flength (spread_arg));
2298 if (numargs == 0)
2299 return Ffuncall (nargs - 1, args);
2300 else if (numargs == 1)
2302 args [nargs - 1] = XCAR (spread_arg);
2303 return Ffuncall (nargs, args);
2306 numargs += nargs - 2;
2308 /* Optimize for no indirection. */
2309 if (SYMBOLP (fun) && !NILP (fun)
2310 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2312 fun = indirect_function (fun);
2313 if (NILP (fun))
2314 /* Let funcall get the error. */
2315 fun = args[0];
2318 if (SUBRP (fun) && XSUBR (fun)->max_args > numargs
2319 /* Don't hide an error by adding missing arguments. */
2320 && numargs >= XSUBR (fun)->min_args)
2322 /* Avoid making funcall cons up a yet another new vector of arguments
2323 by explicitly supplying nil's for optional values. */
2324 SAFE_ALLOCA_LISP (funcall_args, 1 + XSUBR (fun)->max_args);
2325 memclear (funcall_args + numargs + 1,
2326 (XSUBR (fun)->max_args - numargs) * word_size);
2327 funcall_nargs = 1 + XSUBR (fun)->max_args;
2329 else
2330 { /* We add 1 to numargs because funcall_args includes the
2331 function itself as well as its arguments. */
2332 SAFE_ALLOCA_LISP (funcall_args, 1 + numargs);
2333 funcall_nargs = 1 + numargs;
2336 memcpy (funcall_args, args, nargs * word_size);
2337 /* Spread the last arg we got. Its first element goes in
2338 the slot that it used to occupy, hence this value of I. */
2339 i = nargs - 1;
2340 while (!NILP (spread_arg))
2342 funcall_args [i++] = XCAR (spread_arg);
2343 spread_arg = XCDR (spread_arg);
2346 retval = Ffuncall (funcall_nargs, funcall_args);
2348 SAFE_FREE ();
2349 return retval;
2352 /* Run hook variables in various ways. */
2354 static Lisp_Object
2355 funcall_nil (ptrdiff_t nargs, Lisp_Object *args)
2357 Ffuncall (nargs, args);
2358 return Qnil;
2361 DEFUN ("run-hooks", Frun_hooks, Srun_hooks, 0, MANY, 0,
2362 doc: /* Run each hook in HOOKS.
2363 Each argument should be a symbol, a hook variable.
2364 These symbols are processed in the order specified.
2365 If a hook symbol has a non-nil value, that value may be a function
2366 or a list of functions to be called to run the hook.
2367 If the value is a function, it is called with no arguments.
2368 If it is a list, the elements are called, in order, with no arguments.
2370 Major modes should not use this function directly to run their mode
2371 hook; they should use `run-mode-hooks' instead.
2373 Do not use `make-local-variable' to make a hook variable buffer-local.
2374 Instead, use `add-hook' and specify t for the LOCAL argument.
2375 usage: (run-hooks &rest HOOKS) */)
2376 (ptrdiff_t nargs, Lisp_Object *args)
2378 ptrdiff_t i;
2380 for (i = 0; i < nargs; i++)
2381 run_hook (args[i]);
2383 return Qnil;
2386 DEFUN ("run-hook-with-args", Frun_hook_with_args,
2387 Srun_hook_with_args, 1, MANY, 0,
2388 doc: /* Run HOOK with the specified arguments ARGS.
2389 HOOK should be a symbol, a hook variable. The value of HOOK
2390 may be nil, a function, or a list of functions. Call each
2391 function in order with arguments ARGS. The final return value
2392 is unspecified.
2394 Do not use `make-local-variable' to make a hook variable buffer-local.
2395 Instead, use `add-hook' and specify t for the LOCAL argument.
2396 usage: (run-hook-with-args HOOK &rest ARGS) */)
2397 (ptrdiff_t nargs, Lisp_Object *args)
2399 return run_hook_with_args (nargs, args, funcall_nil);
2402 /* NB this one still documents a specific non-nil return value.
2403 (As did run-hook-with-args and run-hook-with-args-until-failure
2404 until they were changed in 24.1.) */
2405 DEFUN ("run-hook-with-args-until-success", Frun_hook_with_args_until_success,
2406 Srun_hook_with_args_until_success, 1, MANY, 0,
2407 doc: /* Run HOOK with the specified arguments ARGS.
2408 HOOK should be a symbol, a hook variable. The value of HOOK
2409 may be nil, a function, or a list of functions. Call each
2410 function in order with arguments ARGS, stopping at the first
2411 one that returns non-nil, and return that value. Otherwise (if
2412 all functions return nil, or if there are no functions to call),
2413 return nil.
2415 Do not use `make-local-variable' to make a hook variable buffer-local.
2416 Instead, use `add-hook' and specify t for the LOCAL argument.
2417 usage: (run-hook-with-args-until-success HOOK &rest ARGS) */)
2418 (ptrdiff_t nargs, Lisp_Object *args)
2420 return run_hook_with_args (nargs, args, Ffuncall);
2423 static Lisp_Object
2424 funcall_not (ptrdiff_t nargs, Lisp_Object *args)
2426 return NILP (Ffuncall (nargs, args)) ? Qt : Qnil;
2429 DEFUN ("run-hook-with-args-until-failure", Frun_hook_with_args_until_failure,
2430 Srun_hook_with_args_until_failure, 1, MANY, 0,
2431 doc: /* Run HOOK with the specified arguments ARGS.
2432 HOOK should be a symbol, a hook variable. The value of HOOK
2433 may be nil, a function, or a list of functions. Call each
2434 function in order with arguments ARGS, stopping at the first
2435 one that returns nil, and return nil. Otherwise (if all functions
2436 return non-nil, or if there are no functions to call), return non-nil
2437 \(do not rely on the precise return value in this case).
2439 Do not use `make-local-variable' to make a hook variable buffer-local.
2440 Instead, use `add-hook' and specify t for the LOCAL argument.
2441 usage: (run-hook-with-args-until-failure HOOK &rest ARGS) */)
2442 (ptrdiff_t nargs, Lisp_Object *args)
2444 return NILP (run_hook_with_args (nargs, args, funcall_not)) ? Qt : Qnil;
2447 static Lisp_Object
2448 run_hook_wrapped_funcall (ptrdiff_t nargs, Lisp_Object *args)
2450 Lisp_Object tmp = args[0], ret;
2451 args[0] = args[1];
2452 args[1] = tmp;
2453 ret = Ffuncall (nargs, args);
2454 args[1] = args[0];
2455 args[0] = tmp;
2456 return ret;
2459 DEFUN ("run-hook-wrapped", Frun_hook_wrapped, Srun_hook_wrapped, 2, MANY, 0,
2460 doc: /* Run HOOK, passing each function through WRAP-FUNCTION.
2461 I.e. instead of calling each function FUN directly with arguments ARGS,
2462 it calls WRAP-FUNCTION with arguments FUN and ARGS.
2463 As soon as a call to WRAP-FUNCTION returns non-nil, `run-hook-wrapped'
2464 aborts and returns that value.
2465 usage: (run-hook-wrapped HOOK WRAP-FUNCTION &rest ARGS) */)
2466 (ptrdiff_t nargs, Lisp_Object *args)
2468 return run_hook_with_args (nargs, args, run_hook_wrapped_funcall);
2471 /* ARGS[0] should be a hook symbol.
2472 Call each of the functions in the hook value, passing each of them
2473 as arguments all the rest of ARGS (all NARGS - 1 elements).
2474 FUNCALL specifies how to call each function on the hook. */
2476 Lisp_Object
2477 run_hook_with_args (ptrdiff_t nargs, Lisp_Object *args,
2478 Lisp_Object (*funcall) (ptrdiff_t nargs, Lisp_Object *args))
2480 Lisp_Object sym, val, ret = Qnil;
2482 /* If we are dying or still initializing,
2483 don't do anything--it would probably crash if we tried. */
2484 if (NILP (Vrun_hooks))
2485 return Qnil;
2487 sym = args[0];
2488 val = find_symbol_value (sym);
2490 if (EQ (val, Qunbound) || NILP (val))
2491 return ret;
2492 else if (!CONSP (val) || FUNCTIONP (val))
2494 args[0] = val;
2495 return funcall (nargs, args);
2497 else
2499 Lisp_Object global_vals = Qnil;
2501 for (;
2502 CONSP (val) && NILP (ret);
2503 val = XCDR (val))
2505 if (EQ (XCAR (val), Qt))
2507 /* t indicates this hook has a local binding;
2508 it means to run the global binding too. */
2509 global_vals = Fdefault_value (sym);
2510 if (NILP (global_vals)) continue;
2512 if (!CONSP (global_vals) || EQ (XCAR (global_vals), Qlambda))
2514 args[0] = global_vals;
2515 ret = funcall (nargs, args);
2517 else
2519 for (;
2520 CONSP (global_vals) && NILP (ret);
2521 global_vals = XCDR (global_vals))
2523 args[0] = XCAR (global_vals);
2524 /* In a global value, t should not occur. If it does, we
2525 must ignore it to avoid an endless loop. */
2526 if (!EQ (args[0], Qt))
2527 ret = funcall (nargs, args);
2531 else
2533 args[0] = XCAR (val);
2534 ret = funcall (nargs, args);
2538 return ret;
2542 /* Run the hook HOOK, giving each function no args. */
2544 void
2545 run_hook (Lisp_Object hook)
2547 Frun_hook_with_args (1, &hook);
2550 /* Run the hook HOOK, giving each function the two args ARG1 and ARG2. */
2552 void
2553 run_hook_with_args_2 (Lisp_Object hook, Lisp_Object arg1, Lisp_Object arg2)
2555 CALLN (Frun_hook_with_args, hook, arg1, arg2);
2558 /* Apply fn to arg. */
2559 Lisp_Object
2560 apply1 (Lisp_Object fn, Lisp_Object arg)
2562 return NILP (arg) ? Ffuncall (1, &fn) : CALLN (Fapply, fn, arg);
2565 /* Call function fn on no arguments. */
2566 Lisp_Object
2567 call0 (Lisp_Object fn)
2569 return Ffuncall (1, &fn);
2572 /* Call function fn with 1 argument arg1. */
2573 /* ARGSUSED */
2574 Lisp_Object
2575 call1 (Lisp_Object fn, Lisp_Object arg1)
2577 return CALLN (Ffuncall, fn, arg1);
2580 /* Call function fn with 2 arguments arg1, arg2. */
2581 /* ARGSUSED */
2582 Lisp_Object
2583 call2 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2)
2585 return CALLN (Ffuncall, fn, arg1, arg2);
2588 /* Call function fn with 3 arguments arg1, arg2, arg3. */
2589 /* ARGSUSED */
2590 Lisp_Object
2591 call3 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2593 return CALLN (Ffuncall, fn, arg1, arg2, arg3);
2596 /* Call function fn with 4 arguments arg1, arg2, arg3, arg4. */
2597 /* ARGSUSED */
2598 Lisp_Object
2599 call4 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2600 Lisp_Object arg4)
2602 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4);
2605 /* Call function fn with 5 arguments arg1, arg2, arg3, arg4, arg5. */
2606 /* ARGSUSED */
2607 Lisp_Object
2608 call5 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2609 Lisp_Object arg4, Lisp_Object arg5)
2611 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5);
2614 /* Call function fn with 6 arguments arg1, arg2, arg3, arg4, arg5, arg6. */
2615 /* ARGSUSED */
2616 Lisp_Object
2617 call6 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2618 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6)
2620 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6);
2623 /* Call function fn with 7 arguments arg1, arg2, arg3, arg4, arg5, arg6, arg7. */
2624 /* ARGSUSED */
2625 Lisp_Object
2626 call7 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2627 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6, Lisp_Object arg7)
2629 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
2632 DEFUN ("functionp", Ffunctionp, Sfunctionp, 1, 1, 0,
2633 doc: /* Non-nil if OBJECT is a function. */)
2634 (Lisp_Object object)
2636 if (FUNCTIONP (object))
2637 return Qt;
2638 return Qnil;
2641 bool
2642 FUNCTIONP (Lisp_Object object)
2644 if (SYMBOLP (object) && !NILP (Ffboundp (object)))
2646 object = Findirect_function (object, Qt);
2648 if (CONSP (object) && EQ (XCAR (object), Qautoload))
2650 /* Autoloaded symbols are functions, except if they load
2651 macros or keymaps. */
2652 for (int i = 0; i < 4 && CONSP (object); i++)
2653 object = XCDR (object);
2655 return ! (CONSP (object) && !NILP (XCAR (object)));
2659 if (SUBRP (object))
2660 return XSUBR (object)->max_args != UNEVALLED;
2661 else if (COMPILEDP (object))
2662 return true;
2663 else if (CONSP (object))
2665 Lisp_Object car = XCAR (object);
2666 return EQ (car, Qlambda) || EQ (car, Qclosure);
2668 else
2669 return false;
2672 DEFUN ("funcall", Ffuncall, Sfuncall, 1, MANY, 0,
2673 doc: /* Call first argument as a function, passing remaining arguments to it.
2674 Return the value that function returns.
2675 Thus, (funcall \\='cons \\='x \\='y) returns (x . y).
2676 usage: (funcall FUNCTION &rest ARGUMENTS) */)
2677 (ptrdiff_t nargs, Lisp_Object *args)
2679 Lisp_Object fun, original_fun;
2680 Lisp_Object funcar;
2681 ptrdiff_t numargs = nargs - 1;
2682 Lisp_Object val;
2683 ptrdiff_t count;
2685 QUIT;
2687 if (++lisp_eval_depth > max_lisp_eval_depth)
2689 if (max_lisp_eval_depth < 100)
2690 max_lisp_eval_depth = 100;
2691 if (lisp_eval_depth > max_lisp_eval_depth)
2692 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2695 count = record_in_backtrace (args[0], &args[1], nargs - 1);
2697 maybe_gc ();
2699 if (debug_on_next_call)
2700 do_debug_on_call (Qlambda, count);
2702 check_cons_list ();
2704 original_fun = args[0];
2706 retry:
2708 /* Optimize for no indirection. */
2709 fun = original_fun;
2710 if (SYMBOLP (fun) && !NILP (fun)
2711 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2712 fun = indirect_function (fun);
2714 if (SUBRP (fun))
2715 val = funcall_subr (XSUBR (fun), numargs, args + 1);
2716 else if (COMPILEDP (fun))
2717 val = funcall_lambda (fun, numargs, args + 1);
2718 else
2720 if (NILP (fun))
2721 xsignal1 (Qvoid_function, original_fun);
2722 if (!CONSP (fun))
2723 xsignal1 (Qinvalid_function, original_fun);
2724 funcar = XCAR (fun);
2725 if (!SYMBOLP (funcar))
2726 xsignal1 (Qinvalid_function, original_fun);
2727 if (EQ (funcar, Qlambda)
2728 || EQ (funcar, Qclosure))
2729 val = funcall_lambda (fun, numargs, args + 1);
2730 else if (EQ (funcar, Qautoload))
2732 Fautoload_do_load (fun, original_fun, Qnil);
2733 check_cons_list ();
2734 goto retry;
2736 else
2737 xsignal1 (Qinvalid_function, original_fun);
2739 check_cons_list ();
2740 lisp_eval_depth--;
2741 if (backtrace_debug_on_exit (specpdl + count))
2742 val = call_debugger (list2 (Qexit, val));
2743 specpdl_ptr--;
2744 return val;
2748 /* Apply a C subroutine SUBR to the NUMARGS evaluated arguments in ARG_VECTOR
2749 and return the result of evaluation. */
2751 Lisp_Object
2752 funcall_subr (struct Lisp_Subr *subr, ptrdiff_t numargs, Lisp_Object *args)
2754 if (numargs < subr->min_args
2755 || (subr->max_args >= 0 && subr->max_args < numargs))
2757 Lisp_Object fun;
2758 XSETSUBR (fun, subr);
2759 xsignal2 (Qwrong_number_of_arguments, fun, make_number (numargs));
2762 else if (subr->max_args == UNEVALLED)
2764 Lisp_Object fun;
2765 XSETSUBR (fun, subr);
2766 xsignal1 (Qinvalid_function, fun);
2769 else if (subr->max_args == MANY)
2770 return (subr->function.aMANY) (numargs, args);
2771 else
2773 Lisp_Object internal_argbuf[8];
2774 Lisp_Object *internal_args;
2775 if (subr->max_args > numargs)
2777 eassert (subr->max_args <= ARRAYELTS (internal_argbuf));
2778 internal_args = internal_argbuf;
2779 memcpy (internal_args, args, numargs * word_size);
2780 memclear (internal_args + numargs,
2781 (subr->max_args - numargs) * word_size);
2783 else
2784 internal_args = args;
2785 switch (subr->max_args)
2787 case 0:
2788 return (subr->function.a0 ());
2789 case 1:
2790 return (subr->function.a1 (internal_args[0]));
2791 case 2:
2792 return (subr->function.a2
2793 (internal_args[0], internal_args[1]));
2794 case 3:
2795 return (subr->function.a3
2796 (internal_args[0], internal_args[1], internal_args[2]));
2797 case 4:
2798 return (subr->function.a4
2799 (internal_args[0], internal_args[1], internal_args[2],
2800 internal_args[3]));
2801 case 5:
2802 return (subr->function.a5
2803 (internal_args[0], internal_args[1], internal_args[2],
2804 internal_args[3], internal_args[4]));
2805 case 6:
2806 return (subr->function.a6
2807 (internal_args[0], internal_args[1], internal_args[2],
2808 internal_args[3], internal_args[4], internal_args[5]));
2809 case 7:
2810 return (subr->function.a7
2811 (internal_args[0], internal_args[1], internal_args[2],
2812 internal_args[3], internal_args[4], internal_args[5],
2813 internal_args[6]));
2814 case 8:
2815 return (subr->function.a8
2816 (internal_args[0], internal_args[1], internal_args[2],
2817 internal_args[3], internal_args[4], internal_args[5],
2818 internal_args[6], internal_args[7]));
2820 default:
2822 /* If a subr takes more than 8 arguments without using MANY
2823 or UNEVALLED, we need to extend this function to support it.
2824 Until this is done, there is no way to call the function. */
2825 emacs_abort ();
2830 static Lisp_Object
2831 apply_lambda (Lisp_Object fun, Lisp_Object args, ptrdiff_t count)
2833 Lisp_Object args_left;
2834 ptrdiff_t i;
2835 EMACS_INT numargs;
2836 Lisp_Object *arg_vector;
2837 Lisp_Object tem;
2838 USE_SAFE_ALLOCA;
2840 numargs = XFASTINT (Flength (args));
2841 SAFE_ALLOCA_LISP (arg_vector, numargs);
2842 args_left = args;
2844 for (i = 0; i < numargs; )
2846 tem = Fcar (args_left), args_left = Fcdr (args_left);
2847 tem = eval_sub (tem);
2848 arg_vector[i++] = tem;
2851 set_backtrace_args (specpdl + count, arg_vector, i);
2852 tem = funcall_lambda (fun, numargs, arg_vector);
2854 check_cons_list ();
2855 lisp_eval_depth--;
2856 /* Do the debug-on-exit now, while arg_vector still exists. */
2857 if (backtrace_debug_on_exit (specpdl + count))
2858 tem = call_debugger (list2 (Qexit, tem));
2859 SAFE_FREE ();
2860 specpdl_ptr--;
2861 return tem;
2864 /* Apply a Lisp function FUN to the NARGS evaluated arguments in ARG_VECTOR
2865 and return the result of evaluation.
2866 FUN must be either a lambda-expression or a compiled-code object. */
2868 static Lisp_Object
2869 funcall_lambda (Lisp_Object fun, ptrdiff_t nargs,
2870 register Lisp_Object *arg_vector)
2872 Lisp_Object val, syms_left, next, lexenv;
2873 ptrdiff_t count = SPECPDL_INDEX ();
2874 ptrdiff_t i;
2875 bool optional, rest;
2877 if (CONSP (fun))
2879 if (EQ (XCAR (fun), Qclosure))
2881 Lisp_Object cdr = XCDR (fun); /* Drop `closure'. */
2882 if (! CONSP (cdr))
2883 xsignal1 (Qinvalid_function, fun);
2884 fun = cdr;
2885 lexenv = XCAR (fun);
2887 else
2888 lexenv = Qnil;
2889 syms_left = XCDR (fun);
2890 if (CONSP (syms_left))
2891 syms_left = XCAR (syms_left);
2892 else
2893 xsignal1 (Qinvalid_function, fun);
2895 else if (COMPILEDP (fun))
2897 ptrdiff_t size = ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK;
2898 if (size <= COMPILED_STACK_DEPTH)
2899 xsignal1 (Qinvalid_function, fun);
2900 syms_left = AREF (fun, COMPILED_ARGLIST);
2901 if (INTEGERP (syms_left))
2902 /* A byte-code object with an integer args template means we
2903 shouldn't bind any arguments, instead just call the byte-code
2904 interpreter directly; it will push arguments as necessary.
2906 Byte-code objects with a nil args template (the default)
2907 have dynamically-bound arguments, and use the
2908 argument-binding code below instead (as do all interpreted
2909 functions, even lexically bound ones). */
2911 /* If we have not actually read the bytecode string
2912 and constants vector yet, fetch them from the file. */
2913 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2914 Ffetch_bytecode (fun);
2915 return exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2916 AREF (fun, COMPILED_CONSTANTS),
2917 AREF (fun, COMPILED_STACK_DEPTH),
2918 syms_left,
2919 nargs, arg_vector);
2921 lexenv = Qnil;
2923 else
2924 emacs_abort ();
2926 i = optional = rest = 0;
2927 bool previous_optional_or_rest = false;
2928 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
2930 QUIT;
2932 next = XCAR (syms_left);
2933 if (!SYMBOLP (next))
2934 xsignal1 (Qinvalid_function, fun);
2936 if (EQ (next, Qand_rest))
2938 if (rest || previous_optional_or_rest)
2939 xsignal1 (Qinvalid_function, fun);
2940 rest = 1;
2941 previous_optional_or_rest = true;
2943 else if (EQ (next, Qand_optional))
2945 if (optional || rest || previous_optional_or_rest)
2946 xsignal1 (Qinvalid_function, fun);
2947 optional = 1;
2948 previous_optional_or_rest = true;
2950 else
2952 Lisp_Object arg;
2953 if (rest)
2955 arg = Flist (nargs - i, &arg_vector[i]);
2956 i = nargs;
2958 else if (i < nargs)
2959 arg = arg_vector[i++];
2960 else if (!optional)
2961 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2962 else
2963 arg = Qnil;
2965 /* Bind the argument. */
2966 if (!NILP (lexenv) && SYMBOLP (next))
2967 /* Lexically bind NEXT by adding it to the lexenv alist. */
2968 lexenv = Fcons (Fcons (next, arg), lexenv);
2969 else
2970 /* Dynamically bind NEXT. */
2971 specbind (next, arg);
2972 previous_optional_or_rest = false;
2976 if (!NILP (syms_left) || previous_optional_or_rest)
2977 xsignal1 (Qinvalid_function, fun);
2978 else if (i < nargs)
2979 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2981 if (!EQ (lexenv, Vinternal_interpreter_environment))
2982 /* Instantiate a new lexical environment. */
2983 specbind (Qinternal_interpreter_environment, lexenv);
2985 if (CONSP (fun))
2986 val = Fprogn (XCDR (XCDR (fun)));
2987 else
2989 /* If we have not actually read the bytecode string
2990 and constants vector yet, fetch them from the file. */
2991 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2992 Ffetch_bytecode (fun);
2993 val = exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2994 AREF (fun, COMPILED_CONSTANTS),
2995 AREF (fun, COMPILED_STACK_DEPTH),
2996 Qnil, 0, 0);
2999 return unbind_to (count, val);
3002 DEFUN ("func-arity", Ffunc_arity, Sfunc_arity, 1, 1, 0,
3003 doc: /* Return minimum and maximum number of args allowed for FUNCTION.
3004 FUNCTION must be a function of some kind.
3005 The returned value is a cons cell (MIN . MAX). MIN is the minimum number
3006 of args. MAX is the maximum number, or the symbol `many', for a
3007 function with `&rest' args, or `unevalled' for a special form. */)
3008 (Lisp_Object function)
3010 Lisp_Object original;
3011 Lisp_Object funcar;
3012 Lisp_Object result;
3014 original = function;
3016 retry:
3018 /* Optimize for no indirection. */
3019 function = original;
3020 if (SYMBOLP (function) && !NILP (function))
3022 function = XSYMBOL (function)->function;
3023 if (SYMBOLP (function))
3024 function = indirect_function (function);
3027 if (CONSP (function) && EQ (XCAR (function), Qmacro))
3028 function = XCDR (function);
3030 if (SUBRP (function))
3031 result = Fsubr_arity (function);
3032 else if (COMPILEDP (function))
3033 result = lambda_arity (function);
3034 else
3036 if (NILP (function))
3037 xsignal1 (Qvoid_function, original);
3038 if (!CONSP (function))
3039 xsignal1 (Qinvalid_function, original);
3040 funcar = XCAR (function);
3041 if (!SYMBOLP (funcar))
3042 xsignal1 (Qinvalid_function, original);
3043 if (EQ (funcar, Qlambda)
3044 || EQ (funcar, Qclosure))
3045 result = lambda_arity (function);
3046 else if (EQ (funcar, Qautoload))
3048 Fautoload_do_load (function, original, Qnil);
3049 goto retry;
3051 else
3052 xsignal1 (Qinvalid_function, original);
3054 return result;
3057 /* FUN must be either a lambda-expression or a compiled-code object. */
3058 static Lisp_Object
3059 lambda_arity (Lisp_Object fun)
3061 Lisp_Object syms_left;
3063 if (CONSP (fun))
3065 if (EQ (XCAR (fun), Qclosure))
3067 fun = XCDR (fun); /* Drop `closure'. */
3068 CHECK_LIST_CONS (fun, fun);
3070 syms_left = XCDR (fun);
3071 if (CONSP (syms_left))
3072 syms_left = XCAR (syms_left);
3073 else
3074 xsignal1 (Qinvalid_function, fun);
3076 else if (COMPILEDP (fun))
3078 ptrdiff_t size = ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK;
3079 if (size <= COMPILED_STACK_DEPTH)
3080 xsignal1 (Qinvalid_function, fun);
3081 syms_left = AREF (fun, COMPILED_ARGLIST);
3082 if (INTEGERP (syms_left))
3083 return get_byte_code_arity (syms_left);
3085 else
3086 emacs_abort ();
3088 EMACS_INT minargs = 0, maxargs = 0;
3089 bool optional = false;
3090 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
3092 Lisp_Object next = XCAR (syms_left);
3093 if (!SYMBOLP (next))
3094 xsignal1 (Qinvalid_function, fun);
3096 if (EQ (next, Qand_rest))
3097 return Fcons (make_number (minargs), Qmany);
3098 else if (EQ (next, Qand_optional))
3099 optional = true;
3100 else
3102 if (!optional)
3103 minargs++;
3104 maxargs++;
3108 if (!NILP (syms_left))
3109 xsignal1 (Qinvalid_function, fun);
3111 return Fcons (make_number (minargs), make_number (maxargs));
3114 DEFUN ("fetch-bytecode", Ffetch_bytecode, Sfetch_bytecode,
3115 1, 1, 0,
3116 doc: /* If byte-compiled OBJECT is lazy-loaded, fetch it now. */)
3117 (Lisp_Object object)
3119 Lisp_Object tem;
3121 if (COMPILEDP (object))
3123 ptrdiff_t size = ASIZE (object) & PSEUDOVECTOR_SIZE_MASK;
3124 if (size <= COMPILED_STACK_DEPTH)
3125 xsignal1 (Qinvalid_function, object);
3126 if (CONSP (AREF (object, COMPILED_BYTECODE)))
3128 tem = read_doc_string (AREF (object, COMPILED_BYTECODE));
3129 if (!CONSP (tem))
3131 tem = AREF (object, COMPILED_BYTECODE);
3132 if (CONSP (tem) && STRINGP (XCAR (tem)))
3133 error ("Invalid byte code in %s", SDATA (XCAR (tem)));
3134 else
3135 error ("Invalid byte code");
3137 ASET (object, COMPILED_BYTECODE, XCAR (tem));
3138 ASET (object, COMPILED_CONSTANTS, XCDR (tem));
3141 return object;
3144 /* Return true if SYMBOL currently has a let-binding
3145 which was made in the buffer that is now current. */
3147 bool
3148 let_shadows_buffer_binding_p (struct Lisp_Symbol *symbol)
3150 union specbinding *p;
3151 Lisp_Object buf = Fcurrent_buffer ();
3153 for (p = specpdl_ptr; p > specpdl; )
3154 if ((--p)->kind > SPECPDL_LET)
3156 struct Lisp_Symbol *let_bound_symbol = XSYMBOL (specpdl_symbol (p));
3157 eassert (let_bound_symbol->redirect != SYMBOL_VARALIAS);
3158 if (symbol == let_bound_symbol
3159 && EQ (specpdl_where (p), buf))
3160 return 1;
3163 return 0;
3166 bool
3167 let_shadows_global_binding_p (Lisp_Object symbol)
3169 union specbinding *p;
3171 for (p = specpdl_ptr; p > specpdl; )
3172 if ((--p)->kind >= SPECPDL_LET && EQ (specpdl_symbol (p), symbol))
3173 return 1;
3175 return 0;
3178 /* `specpdl_ptr' describes which variable is
3179 let-bound, so it can be properly undone when we unbind_to.
3180 It can be either a plain SPECPDL_LET or a SPECPDL_LET_LOCAL/DEFAULT.
3181 - SYMBOL is the variable being bound. Note that it should not be
3182 aliased (i.e. when let-binding V1 that's aliased to V2, we want
3183 to record V2 here).
3184 - WHERE tells us in which buffer the binding took place.
3185 This is used for SPECPDL_LET_LOCAL bindings (i.e. bindings to a
3186 buffer-local variable) as well as for SPECPDL_LET_DEFAULT bindings,
3187 i.e. bindings to the default value of a variable which can be
3188 buffer-local. */
3190 void
3191 specbind (Lisp_Object symbol, Lisp_Object value)
3193 struct Lisp_Symbol *sym;
3195 CHECK_SYMBOL (symbol);
3196 sym = XSYMBOL (symbol);
3198 start:
3199 switch (sym->redirect)
3201 case SYMBOL_VARALIAS:
3202 sym = indirect_variable (sym); XSETSYMBOL (symbol, sym); goto start;
3203 case SYMBOL_PLAINVAL:
3204 /* The most common case is that of a non-constant symbol with a
3205 trivial value. Make that as fast as we can. */
3206 specpdl_ptr->let.kind = SPECPDL_LET;
3207 specpdl_ptr->let.symbol = symbol;
3208 specpdl_ptr->let.old_value = SYMBOL_VAL (sym);
3209 grow_specpdl ();
3210 if (!sym->trapped_write)
3211 SET_SYMBOL_VAL (sym, value);
3212 else
3213 set_internal (symbol, value, Qnil, SET_INTERNAL_BIND);
3214 break;
3215 case SYMBOL_LOCALIZED:
3216 if (SYMBOL_BLV (sym)->frame_local)
3217 error ("Frame-local vars cannot be let-bound");
3218 case SYMBOL_FORWARDED:
3220 Lisp_Object ovalue = find_symbol_value (symbol);
3221 specpdl_ptr->let.kind = SPECPDL_LET_LOCAL;
3222 specpdl_ptr->let.symbol = symbol;
3223 specpdl_ptr->let.old_value = ovalue;
3224 specpdl_ptr->let.where = Fcurrent_buffer ();
3226 eassert (sym->redirect != SYMBOL_LOCALIZED
3227 || (EQ (SYMBOL_BLV (sym)->where, Fcurrent_buffer ())));
3229 if (sym->redirect == SYMBOL_LOCALIZED)
3231 if (!blv_found (SYMBOL_BLV (sym)))
3232 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3234 else if (BUFFER_OBJFWDP (SYMBOL_FWD (sym)))
3236 /* If SYMBOL is a per-buffer variable which doesn't have a
3237 buffer-local value here, make the `let' change the global
3238 value by changing the value of SYMBOL in all buffers not
3239 having their own value. This is consistent with what
3240 happens with other buffer-local variables. */
3241 if (NILP (Flocal_variable_p (symbol, Qnil)))
3243 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3244 grow_specpdl ();
3245 Fset_default (symbol, value);
3246 return;
3249 else
3250 specpdl_ptr->let.kind = SPECPDL_LET;
3252 grow_specpdl ();
3253 set_internal (symbol, value, Qnil, SET_INTERNAL_BIND);
3254 break;
3256 default: emacs_abort ();
3260 /* Push unwind-protect entries of various types. */
3262 void
3263 record_unwind_protect (void (*function) (Lisp_Object), Lisp_Object arg)
3265 specpdl_ptr->unwind.kind = SPECPDL_UNWIND;
3266 specpdl_ptr->unwind.func = function;
3267 specpdl_ptr->unwind.arg = arg;
3268 grow_specpdl ();
3271 void
3272 record_unwind_protect_ptr (void (*function) (void *), void *arg)
3274 specpdl_ptr->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3275 specpdl_ptr->unwind_ptr.func = function;
3276 specpdl_ptr->unwind_ptr.arg = arg;
3277 grow_specpdl ();
3280 void
3281 record_unwind_protect_int (void (*function) (int), int arg)
3283 specpdl_ptr->unwind_int.kind = SPECPDL_UNWIND_INT;
3284 specpdl_ptr->unwind_int.func = function;
3285 specpdl_ptr->unwind_int.arg = arg;
3286 grow_specpdl ();
3289 void
3290 record_unwind_protect_void (void (*function) (void))
3292 specpdl_ptr->unwind_void.kind = SPECPDL_UNWIND_VOID;
3293 specpdl_ptr->unwind_void.func = function;
3294 grow_specpdl ();
3297 static void
3298 do_nothing (void)
3301 /* Push an unwind-protect entry that does nothing, so that
3302 set_unwind_protect_ptr can overwrite it later. */
3304 void
3305 record_unwind_protect_nothing (void)
3307 record_unwind_protect_void (do_nothing);
3310 /* Clear the unwind-protect entry COUNT, so that it does nothing.
3311 It need not be at the top of the stack. */
3313 void
3314 clear_unwind_protect (ptrdiff_t count)
3316 union specbinding *p = specpdl + count;
3317 p->unwind_void.kind = SPECPDL_UNWIND_VOID;
3318 p->unwind_void.func = do_nothing;
3321 /* Set the unwind-protect entry COUNT so that it invokes FUNC (ARG).
3322 It need not be at the top of the stack. Discard the entry's
3323 previous value without invoking it. */
3325 void
3326 set_unwind_protect (ptrdiff_t count, void (*func) (Lisp_Object),
3327 Lisp_Object arg)
3329 union specbinding *p = specpdl + count;
3330 p->unwind.kind = SPECPDL_UNWIND;
3331 p->unwind.func = func;
3332 p->unwind.arg = arg;
3335 void
3336 set_unwind_protect_ptr (ptrdiff_t count, void (*func) (void *), void *arg)
3338 union specbinding *p = specpdl + count;
3339 p->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3340 p->unwind_ptr.func = func;
3341 p->unwind_ptr.arg = arg;
3344 /* Pop and execute entries from the unwind-protect stack until the
3345 depth COUNT is reached. Return VALUE. */
3347 Lisp_Object
3348 unbind_to (ptrdiff_t count, Lisp_Object value)
3350 Lisp_Object quitf = Vquit_flag;
3352 Vquit_flag = Qnil;
3354 while (specpdl_ptr != specpdl + count)
3356 /* Decrement specpdl_ptr before we do the work to unbind it, so
3357 that an error in unbinding won't try to unbind the same entry
3358 again. Take care to copy any parts of the binding needed
3359 before invoking any code that can make more bindings. */
3361 specpdl_ptr--;
3363 switch (specpdl_ptr->kind)
3365 case SPECPDL_UNWIND:
3366 specpdl_ptr->unwind.func (specpdl_ptr->unwind.arg);
3367 break;
3368 case SPECPDL_UNWIND_PTR:
3369 specpdl_ptr->unwind_ptr.func (specpdl_ptr->unwind_ptr.arg);
3370 break;
3371 case SPECPDL_UNWIND_INT:
3372 specpdl_ptr->unwind_int.func (specpdl_ptr->unwind_int.arg);
3373 break;
3374 case SPECPDL_UNWIND_VOID:
3375 specpdl_ptr->unwind_void.func ();
3376 break;
3377 case SPECPDL_BACKTRACE:
3378 break;
3379 case SPECPDL_LET:
3380 { /* If variable has a trivial value (no forwarding), and
3381 isn't trapped, we can just set it. */
3382 Lisp_Object sym = specpdl_symbol (specpdl_ptr);
3383 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3385 if (XSYMBOL (sym)->trapped_write == SYMBOL_UNTRAPPED_WRITE)
3386 SET_SYMBOL_VAL (XSYMBOL (sym), specpdl_old_value (specpdl_ptr));
3387 else
3388 set_internal (sym, specpdl_old_value (specpdl_ptr),
3389 Qnil, SET_INTERNAL_UNBIND);
3390 break;
3392 else
3393 { /* FALLTHROUGH!!
3394 NOTE: we only ever come here if make_local_foo was used for
3395 the first time on this var within this let. */
3398 case SPECPDL_LET_DEFAULT:
3399 Fset_default (specpdl_symbol (specpdl_ptr),
3400 specpdl_old_value (specpdl_ptr));
3401 break;
3402 case SPECPDL_LET_LOCAL:
3404 Lisp_Object symbol = specpdl_symbol (specpdl_ptr);
3405 Lisp_Object where = specpdl_where (specpdl_ptr);
3406 Lisp_Object old_value = specpdl_old_value (specpdl_ptr);
3407 eassert (BUFFERP (where));
3409 /* If this was a local binding, reset the value in the appropriate
3410 buffer, but only if that buffer's binding still exists. */
3411 if (!NILP (Flocal_variable_p (symbol, where)))
3412 set_internal (symbol, old_value, where, SET_INTERNAL_UNBIND);
3414 break;
3418 if (NILP (Vquit_flag) && !NILP (quitf))
3419 Vquit_flag = quitf;
3421 return value;
3424 DEFUN ("special-variable-p", Fspecial_variable_p, Sspecial_variable_p, 1, 1, 0,
3425 doc: /* Return non-nil if SYMBOL's global binding has been declared special.
3426 A special variable is one that will be bound dynamically, even in a
3427 context where binding is lexical by default. */)
3428 (Lisp_Object symbol)
3430 CHECK_SYMBOL (symbol);
3431 return XSYMBOL (symbol)->declared_special ? Qt : Qnil;
3435 DEFUN ("backtrace-debug", Fbacktrace_debug, Sbacktrace_debug, 2, 2, 0,
3436 doc: /* Set the debug-on-exit flag of eval frame LEVEL levels down to FLAG.
3437 The debugger is entered when that frame exits, if the flag is non-nil. */)
3438 (Lisp_Object level, Lisp_Object flag)
3440 union specbinding *pdl = backtrace_top ();
3441 register EMACS_INT i;
3443 CHECK_NUMBER (level);
3445 for (i = 0; backtrace_p (pdl) && i < XINT (level); i++)
3446 pdl = backtrace_next (pdl);
3448 if (backtrace_p (pdl))
3449 set_backtrace_debug_on_exit (pdl, !NILP (flag));
3451 return flag;
3454 DEFUN ("backtrace", Fbacktrace, Sbacktrace, 0, 0, "",
3455 doc: /* Print a trace of Lisp function calls currently active.
3456 Output stream used is value of `standard-output'. */)
3457 (void)
3459 union specbinding *pdl = backtrace_top ();
3460 Lisp_Object tem;
3461 Lisp_Object old_print_level = Vprint_level;
3463 if (NILP (Vprint_level))
3464 XSETFASTINT (Vprint_level, 8);
3466 while (backtrace_p (pdl))
3468 write_string (backtrace_debug_on_exit (pdl) ? "* " : " ");
3469 if (backtrace_nargs (pdl) == UNEVALLED)
3471 Fprin1 (Fcons (backtrace_function (pdl), *backtrace_args (pdl)),
3472 Qnil);
3473 write_string ("\n");
3475 else
3477 tem = backtrace_function (pdl);
3478 if (debugger_stack_frame_as_list)
3479 write_string ("(");
3480 Fprin1 (tem, Qnil); /* This can QUIT. */
3481 if (!debugger_stack_frame_as_list)
3482 write_string ("(");
3484 ptrdiff_t i;
3485 for (i = 0; i < backtrace_nargs (pdl); i++)
3487 if (i || debugger_stack_frame_as_list)
3488 write_string(" ");
3489 Fprin1 (backtrace_args (pdl)[i], Qnil);
3492 write_string (")\n");
3494 pdl = backtrace_next (pdl);
3497 Vprint_level = old_print_level;
3498 return Qnil;
3501 static union specbinding *
3502 get_backtrace_frame (Lisp_Object nframes, Lisp_Object base)
3504 union specbinding *pdl = backtrace_top ();
3505 register EMACS_INT i;
3507 CHECK_NATNUM (nframes);
3509 if (!NILP (base))
3510 { /* Skip up to `base'. */
3511 base = Findirect_function (base, Qt);
3512 while (backtrace_p (pdl)
3513 && !EQ (base, Findirect_function (backtrace_function (pdl), Qt)))
3514 pdl = backtrace_next (pdl);
3517 /* Find the frame requested. */
3518 for (i = XFASTINT (nframes); i > 0 && backtrace_p (pdl); i--)
3519 pdl = backtrace_next (pdl);
3521 return pdl;
3524 DEFUN ("backtrace-frame", Fbacktrace_frame, Sbacktrace_frame, 1, 2, NULL,
3525 doc: /* Return the function and arguments NFRAMES up from current execution point.
3526 If that frame has not evaluated the arguments yet (or is a special form),
3527 the value is (nil FUNCTION ARG-FORMS...).
3528 If that frame has evaluated its arguments and called its function already,
3529 the value is (t FUNCTION ARG-VALUES...).
3530 A &rest arg is represented as the tail of the list ARG-VALUES.
3531 FUNCTION is whatever was supplied as car of evaluated list,
3532 or a lambda expression for macro calls.
3533 If NFRAMES is more than the number of frames, the value is nil.
3534 If BASE is non-nil, it should be a function and NFRAMES counts from its
3535 nearest activation frame. */)
3536 (Lisp_Object nframes, Lisp_Object base)
3538 union specbinding *pdl = get_backtrace_frame (nframes, base);
3540 if (!backtrace_p (pdl))
3541 return Qnil;
3542 if (backtrace_nargs (pdl) == UNEVALLED)
3543 return Fcons (Qnil,
3544 Fcons (backtrace_function (pdl), *backtrace_args (pdl)));
3545 else
3547 Lisp_Object tem = Flist (backtrace_nargs (pdl), backtrace_args (pdl));
3549 return Fcons (Qt, Fcons (backtrace_function (pdl), tem));
3553 /* For backtrace-eval, we want to temporarily unwind the last few elements of
3554 the specpdl stack, and then rewind them. We store the pre-unwind values
3555 directly in the pre-existing specpdl elements (i.e. we swap the current
3556 value and the old value stored in the specpdl), kind of like the inplace
3557 pointer-reversal trick. As it turns out, the rewind does the same as the
3558 unwind, except it starts from the other end of the specpdl stack, so we use
3559 the same function for both unwind and rewind. */
3560 static void
3561 backtrace_eval_unrewind (int distance)
3563 union specbinding *tmp = specpdl_ptr;
3564 int step = -1;
3565 if (distance < 0)
3566 { /* It's a rewind rather than unwind. */
3567 tmp += distance - 1;
3568 step = 1;
3569 distance = -distance;
3572 for (; distance > 0; distance--)
3574 tmp += step;
3575 switch (tmp->kind)
3577 /* FIXME: Ideally we'd like to "temporarily unwind" (some of) those
3578 unwind_protect, but the problem is that we don't know how to
3579 rewind them afterwards. */
3580 case SPECPDL_UNWIND:
3582 Lisp_Object oldarg = tmp->unwind.arg;
3583 if (tmp->unwind.func == set_buffer_if_live)
3584 tmp->unwind.arg = Fcurrent_buffer ();
3585 else if (tmp->unwind.func == save_excursion_restore)
3586 tmp->unwind.arg = save_excursion_save ();
3587 else
3588 break;
3589 tmp->unwind.func (oldarg);
3590 break;
3593 case SPECPDL_UNWIND_PTR:
3594 case SPECPDL_UNWIND_INT:
3595 case SPECPDL_UNWIND_VOID:
3596 case SPECPDL_BACKTRACE:
3597 break;
3598 case SPECPDL_LET:
3599 { /* If variable has a trivial value (no forwarding), we can
3600 just set it. No need to check for constant symbols here,
3601 since that was already done by specbind. */
3602 Lisp_Object sym = specpdl_symbol (tmp);
3603 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3605 Lisp_Object old_value = specpdl_old_value (tmp);
3606 set_specpdl_old_value (tmp, SYMBOL_VAL (XSYMBOL (sym)));
3607 SET_SYMBOL_VAL (XSYMBOL (sym), old_value);
3608 break;
3610 else
3611 { /* FALLTHROUGH!!
3612 NOTE: we only ever come here if make_local_foo was used for
3613 the first time on this var within this let. */
3616 case SPECPDL_LET_DEFAULT:
3618 Lisp_Object sym = specpdl_symbol (tmp);
3619 Lisp_Object old_value = specpdl_old_value (tmp);
3620 set_specpdl_old_value (tmp, Fdefault_value (sym));
3621 Fset_default (sym, old_value);
3623 break;
3624 case SPECPDL_LET_LOCAL:
3626 Lisp_Object symbol = specpdl_symbol (tmp);
3627 Lisp_Object where = specpdl_where (tmp);
3628 Lisp_Object old_value = specpdl_old_value (tmp);
3629 eassert (BUFFERP (where));
3631 /* If this was a local binding, reset the value in the appropriate
3632 buffer, but only if that buffer's binding still exists. */
3633 if (!NILP (Flocal_variable_p (symbol, where)))
3635 set_specpdl_old_value
3636 (tmp, Fbuffer_local_value (symbol, where));
3637 set_internal (symbol, old_value, where, SET_INTERNAL_UNBIND);
3640 break;
3645 DEFUN ("backtrace-eval", Fbacktrace_eval, Sbacktrace_eval, 2, 3, NULL,
3646 doc: /* Evaluate EXP in the context of some activation frame.
3647 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3648 (Lisp_Object exp, Lisp_Object nframes, Lisp_Object base)
3650 union specbinding *pdl = get_backtrace_frame (nframes, base);
3651 ptrdiff_t count = SPECPDL_INDEX ();
3652 ptrdiff_t distance = specpdl_ptr - pdl;
3653 eassert (distance >= 0);
3655 if (!backtrace_p (pdl))
3656 error ("Activation frame not found!");
3658 backtrace_eval_unrewind (distance);
3659 record_unwind_protect_int (backtrace_eval_unrewind, -distance);
3661 /* Use eval_sub rather than Feval since the main motivation behind
3662 backtrace-eval is to be able to get/set the value of lexical variables
3663 from the debugger. */
3664 return unbind_to (count, eval_sub (exp));
3667 DEFUN ("backtrace--locals", Fbacktrace__locals, Sbacktrace__locals, 1, 2, NULL,
3668 doc: /* Return names and values of local variables of a stack frame.
3669 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3670 (Lisp_Object nframes, Lisp_Object base)
3672 union specbinding *frame = get_backtrace_frame (nframes, base);
3673 union specbinding *prevframe
3674 = get_backtrace_frame (make_number (XFASTINT (nframes) - 1), base);
3675 ptrdiff_t distance = specpdl_ptr - frame;
3676 Lisp_Object result = Qnil;
3677 eassert (distance >= 0);
3679 if (!backtrace_p (prevframe))
3680 error ("Activation frame not found!");
3681 if (!backtrace_p (frame))
3682 error ("Activation frame not found!");
3684 /* The specpdl entries normally contain the symbol being bound along with its
3685 `old_value', so it can be restored. The new value to which it is bound is
3686 available in one of two places: either in the current value of the
3687 variable (if it hasn't been rebound yet) or in the `old_value' slot of the
3688 next specpdl entry for it.
3689 `backtrace_eval_unrewind' happens to swap the role of `old_value'
3690 and "new value", so we abuse it here, to fetch the new value.
3691 It's ugly (we'd rather not modify global data) and a bit inefficient,
3692 but it does the job for now. */
3693 backtrace_eval_unrewind (distance);
3695 /* Grab values. */
3697 union specbinding *tmp = prevframe;
3698 for (; tmp > frame; tmp--)
3700 switch (tmp->kind)
3702 case SPECPDL_LET:
3703 case SPECPDL_LET_DEFAULT:
3704 case SPECPDL_LET_LOCAL:
3706 Lisp_Object sym = specpdl_symbol (tmp);
3707 Lisp_Object val = specpdl_old_value (tmp);
3708 if (EQ (sym, Qinternal_interpreter_environment))
3710 Lisp_Object env = val;
3711 for (; CONSP (env); env = XCDR (env))
3713 Lisp_Object binding = XCAR (env);
3714 if (CONSP (binding))
3715 result = Fcons (Fcons (XCAR (binding),
3716 XCDR (binding)),
3717 result);
3720 else
3721 result = Fcons (Fcons (sym, val), result);
3723 break;
3725 case SPECPDL_UNWIND:
3726 case SPECPDL_UNWIND_PTR:
3727 case SPECPDL_UNWIND_INT:
3728 case SPECPDL_UNWIND_VOID:
3729 case SPECPDL_BACKTRACE:
3730 break;
3732 default:
3733 emacs_abort ();
3738 /* Restore values from specpdl to original place. */
3739 backtrace_eval_unrewind (-distance);
3741 return result;
3745 void
3746 mark_specpdl (void)
3748 union specbinding *pdl;
3749 for (pdl = specpdl; pdl != specpdl_ptr; pdl++)
3751 switch (pdl->kind)
3753 case SPECPDL_UNWIND:
3754 mark_object (specpdl_arg (pdl));
3755 break;
3757 case SPECPDL_BACKTRACE:
3759 ptrdiff_t nargs = backtrace_nargs (pdl);
3760 mark_object (backtrace_function (pdl));
3761 if (nargs == UNEVALLED)
3762 nargs = 1;
3763 while (nargs--)
3764 mark_object (backtrace_args (pdl)[nargs]);
3766 break;
3768 case SPECPDL_LET_DEFAULT:
3769 case SPECPDL_LET_LOCAL:
3770 mark_object (specpdl_where (pdl));
3771 /* Fall through. */
3772 case SPECPDL_LET:
3773 mark_object (specpdl_symbol (pdl));
3774 mark_object (specpdl_old_value (pdl));
3775 break;
3777 case SPECPDL_UNWIND_PTR:
3778 case SPECPDL_UNWIND_INT:
3779 case SPECPDL_UNWIND_VOID:
3780 break;
3782 default:
3783 emacs_abort ();
3788 void
3789 get_backtrace (Lisp_Object array)
3791 union specbinding *pdl = backtrace_next (backtrace_top ());
3792 ptrdiff_t i = 0, asize = ASIZE (array);
3794 /* Copy the backtrace contents into working memory. */
3795 for (; i < asize; i++)
3797 if (backtrace_p (pdl))
3799 ASET (array, i, backtrace_function (pdl));
3800 pdl = backtrace_next (pdl);
3802 else
3803 ASET (array, i, Qnil);
3807 Lisp_Object backtrace_top_function (void)
3809 union specbinding *pdl = backtrace_top ();
3810 return (backtrace_p (pdl) ? backtrace_function (pdl) : Qnil);
3813 void
3814 syms_of_eval (void)
3816 DEFVAR_INT ("max-specpdl-size", max_specpdl_size,
3817 doc: /* Limit on number of Lisp variable bindings and `unwind-protect's.
3818 If Lisp code tries to increase the total number past this amount,
3819 an error is signaled.
3820 You can safely use a value considerably larger than the default value,
3821 if that proves inconveniently small. However, if you increase it too far,
3822 Emacs could run out of memory trying to make the stack bigger.
3823 Note that this limit may be silently increased by the debugger
3824 if `debug-on-error' or `debug-on-quit' is set. */);
3826 DEFVAR_INT ("max-lisp-eval-depth", max_lisp_eval_depth,
3827 doc: /* Limit on depth in `eval', `apply' and `funcall' before error.
3829 This limit serves to catch infinite recursions for you before they cause
3830 actual stack overflow in C, which would be fatal for Emacs.
3831 You can safely make it considerably larger than its default value,
3832 if that proves inconveniently small. However, if you increase it too far,
3833 Emacs could overflow the real C stack, and crash. */);
3835 DEFVAR_LISP ("quit-flag", Vquit_flag,
3836 doc: /* Non-nil causes `eval' to abort, unless `inhibit-quit' is non-nil.
3837 If the value is t, that means do an ordinary quit.
3838 If the value equals `throw-on-input', that means quit by throwing
3839 to the tag specified in `throw-on-input'; it's for handling `while-no-input'.
3840 Typing C-g sets `quit-flag' to t, regardless of `inhibit-quit',
3841 but `inhibit-quit' non-nil prevents anything from taking notice of that. */);
3842 Vquit_flag = Qnil;
3844 DEFVAR_LISP ("inhibit-quit", Vinhibit_quit,
3845 doc: /* Non-nil inhibits C-g quitting from happening immediately.
3846 Note that `quit-flag' will still be set by typing C-g,
3847 so a quit will be signaled as soon as `inhibit-quit' is nil.
3848 To prevent this happening, set `quit-flag' to nil
3849 before making `inhibit-quit' nil. */);
3850 Vinhibit_quit = Qnil;
3852 DEFSYM (Qsetq, "setq");
3853 DEFSYM (Qinhibit_quit, "inhibit-quit");
3854 DEFSYM (Qautoload, "autoload");
3855 DEFSYM (Qinhibit_debugger, "inhibit-debugger");
3856 DEFSYM (Qmacro, "macro");
3858 /* Note that the process handling also uses Qexit, but we don't want
3859 to staticpro it twice, so we just do it here. */
3860 DEFSYM (Qexit, "exit");
3862 DEFSYM (Qinteractive, "interactive");
3863 DEFSYM (Qcommandp, "commandp");
3864 DEFSYM (Qand_rest, "&rest");
3865 DEFSYM (Qand_optional, "&optional");
3866 DEFSYM (Qclosure, "closure");
3867 DEFSYM (QCdocumentation, ":documentation");
3868 DEFSYM (Qdebug, "debug");
3870 DEFVAR_LISP ("inhibit-debugger", Vinhibit_debugger,
3871 doc: /* Non-nil means never enter the debugger.
3872 Normally set while the debugger is already active, to avoid recursive
3873 invocations. */);
3874 Vinhibit_debugger = Qnil;
3876 DEFVAR_LISP ("debug-on-error", Vdebug_on_error,
3877 doc: /* Non-nil means enter debugger if an error is signaled.
3878 Does not apply to errors handled by `condition-case' or those
3879 matched by `debug-ignored-errors'.
3880 If the value is a list, an error only means to enter the debugger
3881 if one of its condition symbols appears in the list.
3882 When you evaluate an expression interactively, this variable
3883 is temporarily non-nil if `eval-expression-debug-on-error' is non-nil.
3884 The command `toggle-debug-on-error' toggles this.
3885 See also the variable `debug-on-quit' and `inhibit-debugger'. */);
3886 Vdebug_on_error = Qnil;
3888 DEFVAR_LISP ("debug-ignored-errors", Vdebug_ignored_errors,
3889 doc: /* List of errors for which the debugger should not be called.
3890 Each element may be a condition-name or a regexp that matches error messages.
3891 If any element applies to a given error, that error skips the debugger
3892 and just returns to top level.
3893 This overrides the variable `debug-on-error'.
3894 It does not apply to errors handled by `condition-case'. */);
3895 Vdebug_ignored_errors = Qnil;
3897 DEFVAR_BOOL ("debug-on-quit", debug_on_quit,
3898 doc: /* Non-nil means enter debugger if quit is signaled (C-g, for example).
3899 Does not apply if quit is handled by a `condition-case'. */);
3900 debug_on_quit = 0;
3902 DEFVAR_BOOL ("debug-on-next-call", debug_on_next_call,
3903 doc: /* Non-nil means enter debugger before next `eval', `apply' or `funcall'. */);
3905 DEFVAR_BOOL ("debugger-may-continue", debugger_may_continue,
3906 doc: /* Non-nil means debugger may continue execution.
3907 This is nil when the debugger is called under circumstances where it
3908 might not be safe to continue. */);
3909 debugger_may_continue = 1;
3911 DEFVAR_BOOL ("debugger-stack-frame-as-list", debugger_stack_frame_as_list,
3912 doc: /* Non-nil means display call stack frames as lists. */);
3913 debugger_stack_frame_as_list = 0;
3915 DEFVAR_LISP ("debugger", Vdebugger,
3916 doc: /* Function to call to invoke debugger.
3917 If due to frame exit, args are `exit' and the value being returned;
3918 this function's value will be returned instead of that.
3919 If due to error, args are `error' and a list of the args to `signal'.
3920 If due to `apply' or `funcall' entry, one arg, `lambda'.
3921 If due to `eval' entry, one arg, t. */);
3922 Vdebugger = Qnil;
3924 DEFVAR_LISP ("signal-hook-function", Vsignal_hook_function,
3925 doc: /* If non-nil, this is a function for `signal' to call.
3926 It receives the same arguments that `signal' was given.
3927 The Edebug package uses this to regain control. */);
3928 Vsignal_hook_function = Qnil;
3930 DEFVAR_LISP ("debug-on-signal", Vdebug_on_signal,
3931 doc: /* Non-nil means call the debugger regardless of condition handlers.
3932 Note that `debug-on-error', `debug-on-quit' and friends
3933 still determine whether to handle the particular condition. */);
3934 Vdebug_on_signal = Qnil;
3936 /* When lexical binding is being used,
3937 Vinternal_interpreter_environment is non-nil, and contains an alist
3938 of lexically-bound variable, or (t), indicating an empty
3939 environment. The lisp name of this variable would be
3940 `internal-interpreter-environment' if it weren't hidden.
3941 Every element of this list can be either a cons (VAR . VAL)
3942 specifying a lexical binding, or a single symbol VAR indicating
3943 that this variable should use dynamic scoping. */
3944 DEFSYM (Qinternal_interpreter_environment,
3945 "internal-interpreter-environment");
3946 DEFVAR_LISP ("internal-interpreter-environment",
3947 Vinternal_interpreter_environment,
3948 doc: /* If non-nil, the current lexical environment of the lisp interpreter.
3949 When lexical binding is not being used, this variable is nil.
3950 A value of `(t)' indicates an empty environment, otherwise it is an
3951 alist of active lexical bindings. */);
3952 Vinternal_interpreter_environment = Qnil;
3953 /* Don't export this variable to Elisp, so no one can mess with it
3954 (Just imagine if someone makes it buffer-local). */
3955 Funintern (Qinternal_interpreter_environment, Qnil);
3957 Vrun_hooks = intern_c_string ("run-hooks");
3958 staticpro (&Vrun_hooks);
3960 staticpro (&Vautoload_queue);
3961 Vautoload_queue = Qnil;
3962 staticpro (&Vsignaling_function);
3963 Vsignaling_function = Qnil;
3965 inhibit_lisp_code = Qnil;
3967 defsubr (&Sor);
3968 defsubr (&Sand);
3969 defsubr (&Sif);
3970 defsubr (&Scond);
3971 defsubr (&Sprogn);
3972 defsubr (&Sprog1);
3973 defsubr (&Sprog2);
3974 defsubr (&Ssetq);
3975 defsubr (&Squote);
3976 defsubr (&Sfunction);
3977 defsubr (&Sdefault_toplevel_value);
3978 defsubr (&Sset_default_toplevel_value);
3979 defsubr (&Sdefvar);
3980 defsubr (&Sdefvaralias);
3981 DEFSYM (Qdefvaralias, "defvaralias");
3982 defsubr (&Sdefconst);
3983 defsubr (&Smake_var_non_special);
3984 defsubr (&Slet);
3985 defsubr (&SletX);
3986 defsubr (&Swhile);
3987 defsubr (&Smacroexpand);
3988 defsubr (&Scatch);
3989 defsubr (&Sthrow);
3990 defsubr (&Sunwind_protect);
3991 defsubr (&Scondition_case);
3992 defsubr (&Ssignal);
3993 defsubr (&Scommandp);
3994 defsubr (&Sautoload);
3995 defsubr (&Sautoload_do_load);
3996 defsubr (&Seval);
3997 defsubr (&Sapply);
3998 defsubr (&Sfuncall);
3999 defsubr (&Sfunc_arity);
4000 defsubr (&Srun_hooks);
4001 defsubr (&Srun_hook_with_args);
4002 defsubr (&Srun_hook_with_args_until_success);
4003 defsubr (&Srun_hook_with_args_until_failure);
4004 defsubr (&Srun_hook_wrapped);
4005 defsubr (&Sfetch_bytecode);
4006 defsubr (&Sbacktrace_debug);
4007 defsubr (&Sbacktrace);
4008 defsubr (&Sbacktrace_frame);
4009 defsubr (&Sbacktrace_eval);
4010 defsubr (&Sbacktrace__locals);
4011 defsubr (&Sspecial_variable_p);
4012 defsubr (&Sfunctionp);