Fix `eww-current-source' buffer confustion
[emacs.git] / src / eval.c
blob77b1db9539742695d5ebd592b039a7566789a0b2
1 /* Evaluator for GNU Emacs Lisp interpreter.
3 Copyright (C) 1985-1987, 1993-1995, 1999-2014 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
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
23 #include <limits.h>
24 #include <stdio.h>
25 #include "lisp.h"
26 #include "blockinput.h"
27 #include "commands.h"
28 #include "keyboard.h"
29 #include "dispextern.h"
31 /* Chain of condition and catch handlers currently in effect. */
33 struct handler *handlerlist;
35 #ifdef DEBUG_GCPRO
36 /* Count levels of GCPRO to detect failure to UNGCPRO. */
37 int gcpro_level;
38 #endif
40 Lisp_Object Qautoload, Qmacro, Qexit, Qinteractive, Qcommandp;
41 Lisp_Object Qinhibit_quit;
42 Lisp_Object Qand_rest;
43 static Lisp_Object Qand_optional;
44 static Lisp_Object Qinhibit_debugger;
45 static Lisp_Object Qdeclare;
46 Lisp_Object Qinternal_interpreter_environment, Qclosure;
48 static Lisp_Object Qdebug;
50 /* This holds either the symbol `run-hooks' or nil.
51 It is nil at an early stage of startup, and when Emacs
52 is shutting down. */
54 Lisp_Object Vrun_hooks;
56 /* Non-nil means record all fset's and provide's, to be undone
57 if the file being autoloaded is not fully loaded.
58 They are recorded by being consed onto the front of Vautoload_queue:
59 (FUN . ODEF) for a defun, (0 . OFEATURES) for a provide. */
61 Lisp_Object Vautoload_queue;
63 /* Current number of specbindings allocated in specpdl, not counting
64 the dummy entry specpdl[-1]. */
66 ptrdiff_t specpdl_size;
68 /* Pointer to beginning of specpdl. A dummy entry specpdl[-1] exists
69 only so that its address can be taken. */
71 union specbinding *specpdl;
73 /* Pointer to first unused element in specpdl. */
75 union specbinding *specpdl_ptr;
77 /* Depth in Lisp evaluations and function calls. */
79 EMACS_INT lisp_eval_depth;
81 /* The value of num_nonmacro_input_events as of the last time we
82 started to enter the debugger. If we decide to enter the debugger
83 again when this is still equal to num_nonmacro_input_events, then we
84 know that the debugger itself has an error, and we should just
85 signal the error instead of entering an infinite loop of debugger
86 invocations. */
88 static EMACS_INT when_entered_debugger;
90 /* The function from which the last `signal' was called. Set in
91 Fsignal. */
92 /* FIXME: We should probably get rid of this! */
93 Lisp_Object Vsignaling_function;
95 /* If non-nil, Lisp code must not be run since some part of Emacs is in
96 an inconsistent state. Currently unused. */
97 Lisp_Object inhibit_lisp_code;
99 /* These would ordinarily be static, but they need to be visible to GDB. */
100 bool backtrace_p (union specbinding *) EXTERNALLY_VISIBLE;
101 Lisp_Object *backtrace_args (union specbinding *) EXTERNALLY_VISIBLE;
102 Lisp_Object backtrace_function (union specbinding *) EXTERNALLY_VISIBLE;
103 union specbinding *backtrace_next (union specbinding *) EXTERNALLY_VISIBLE;
104 union specbinding *backtrace_top (void) EXTERNALLY_VISIBLE;
106 static Lisp_Object funcall_lambda (Lisp_Object, ptrdiff_t, Lisp_Object *);
107 static Lisp_Object apply_lambda (Lisp_Object, Lisp_Object, ptrdiff_t);
109 static Lisp_Object
110 specpdl_symbol (union specbinding *pdl)
112 eassert (pdl->kind >= SPECPDL_LET);
113 return pdl->let.symbol;
116 static Lisp_Object
117 specpdl_old_value (union specbinding *pdl)
119 eassert (pdl->kind >= SPECPDL_LET);
120 return pdl->let.old_value;
123 static void
124 set_specpdl_old_value (union specbinding *pdl, Lisp_Object val)
126 eassert (pdl->kind >= SPECPDL_LET);
127 pdl->let.old_value = val;
130 static Lisp_Object
131 specpdl_where (union specbinding *pdl)
133 eassert (pdl->kind > SPECPDL_LET);
134 return pdl->let.where;
137 static Lisp_Object
138 specpdl_arg (union specbinding *pdl)
140 eassert (pdl->kind == SPECPDL_UNWIND);
141 return pdl->unwind.arg;
144 Lisp_Object
145 backtrace_function (union specbinding *pdl)
147 eassert (pdl->kind == SPECPDL_BACKTRACE);
148 return pdl->bt.function;
151 static ptrdiff_t
152 backtrace_nargs (union specbinding *pdl)
154 eassert (pdl->kind == SPECPDL_BACKTRACE);
155 return pdl->bt.nargs;
158 Lisp_Object *
159 backtrace_args (union specbinding *pdl)
161 eassert (pdl->kind == SPECPDL_BACKTRACE);
162 return pdl->bt.args;
165 static bool
166 backtrace_debug_on_exit (union specbinding *pdl)
168 eassert (pdl->kind == SPECPDL_BACKTRACE);
169 return pdl->bt.debug_on_exit;
172 /* Functions to modify slots of backtrace records. */
174 static void
175 set_backtrace_args (union specbinding *pdl, Lisp_Object *args, ptrdiff_t nargs)
177 eassert (pdl->kind == SPECPDL_BACKTRACE);
178 pdl->bt.args = args;
179 pdl->bt.nargs = nargs;
182 static void
183 set_backtrace_debug_on_exit (union specbinding *pdl, bool doe)
185 eassert (pdl->kind == SPECPDL_BACKTRACE);
186 pdl->bt.debug_on_exit = doe;
189 /* Helper functions to scan the backtrace. */
191 bool
192 backtrace_p (union specbinding *pdl)
193 { return pdl >= specpdl; }
195 union specbinding *
196 backtrace_top (void)
198 union specbinding *pdl = specpdl_ptr - 1;
199 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
200 pdl--;
201 return pdl;
204 union specbinding *
205 backtrace_next (union specbinding *pdl)
207 pdl--;
208 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
209 pdl--;
210 return pdl;
214 void
215 init_eval_once (void)
217 enum { size = 50 };
218 union specbinding *pdlvec = xmalloc ((size + 1) * sizeof *specpdl);
219 specpdl_size = size;
220 specpdl = specpdl_ptr = pdlvec + 1;
221 /* Don't forget to update docs (lispref node "Local Variables"). */
222 max_specpdl_size = 1300; /* 1000 is not enough for CEDET's c-by.el. */
223 max_lisp_eval_depth = 600;
225 Vrun_hooks = Qnil;
228 static struct handler handlerlist_sentinel;
230 void
231 init_eval (void)
233 specpdl_ptr = specpdl;
234 { /* Put a dummy catcher at top-level so that handlerlist is never NULL.
235 This is important since handlerlist->nextfree holds the freelist
236 which would otherwise leak every time we unwind back to top-level. */
237 struct handler *c;
238 handlerlist = handlerlist_sentinel.nextfree = &handlerlist_sentinel;
239 PUSH_HANDLER (c, Qunbound, CATCHER);
240 eassert (c == &handlerlist_sentinel);
241 handlerlist_sentinel.nextfree = NULL;
242 handlerlist_sentinel.next = NULL;
244 Vquit_flag = Qnil;
245 debug_on_next_call = 0;
246 lisp_eval_depth = 0;
247 #ifdef DEBUG_GCPRO
248 gcpro_level = 0;
249 #endif
250 /* This is less than the initial value of num_nonmacro_input_events. */
251 when_entered_debugger = -1;
254 /* Unwind-protect function used by call_debugger. */
256 static void
257 restore_stack_limits (Lisp_Object data)
259 max_specpdl_size = XINT (XCAR (data));
260 max_lisp_eval_depth = XINT (XCDR (data));
263 static void grow_specpdl (void);
265 /* Call the Lisp debugger, giving it argument ARG. */
267 Lisp_Object
268 call_debugger (Lisp_Object arg)
270 bool debug_while_redisplaying;
271 ptrdiff_t count = SPECPDL_INDEX ();
272 Lisp_Object val;
273 EMACS_INT old_depth = max_lisp_eval_depth;
274 /* Do not allow max_specpdl_size less than actual depth (Bug#16603). */
275 EMACS_INT old_max = max (max_specpdl_size, count);
277 if (lisp_eval_depth + 40 > max_lisp_eval_depth)
278 max_lisp_eval_depth = lisp_eval_depth + 40;
280 /* While debugging Bug#16603, previous value of 100 was found
281 too small to avoid specpdl overflow in the debugger itself. */
282 if (max_specpdl_size - 200 < count)
283 max_specpdl_size = count + 200;
285 if (old_max == count)
287 /* We can enter the debugger due to specpdl overflow (Bug#16603). */
288 specpdl_ptr--;
289 grow_specpdl ();
292 /* Restore limits after leaving the debugger. */
293 record_unwind_protect (restore_stack_limits,
294 Fcons (make_number (old_max),
295 make_number (old_depth)));
297 #ifdef HAVE_WINDOW_SYSTEM
298 if (display_hourglass_p)
299 cancel_hourglass ();
300 #endif
302 debug_on_next_call = 0;
303 when_entered_debugger = num_nonmacro_input_events;
305 /* Resetting redisplaying_p to 0 makes sure that debug output is
306 displayed if the debugger is invoked during redisplay. */
307 debug_while_redisplaying = redisplaying_p;
308 redisplaying_p = 0;
309 specbind (intern ("debugger-may-continue"),
310 debug_while_redisplaying ? Qnil : Qt);
311 specbind (Qinhibit_redisplay, Qnil);
312 specbind (Qinhibit_debugger, Qt);
314 #if 0 /* Binding this prevents execution of Lisp code during
315 redisplay, which necessarily leads to display problems. */
316 specbind (Qinhibit_eval_during_redisplay, Qt);
317 #endif
319 val = apply1 (Vdebugger, arg);
321 /* Interrupting redisplay and resuming it later is not safe under
322 all circumstances. So, when the debugger returns, abort the
323 interrupted redisplay by going back to the top-level. */
324 if (debug_while_redisplaying)
325 Ftop_level ();
327 return unbind_to (count, val);
330 static void
331 do_debug_on_call (Lisp_Object code, ptrdiff_t count)
333 debug_on_next_call = 0;
334 set_backtrace_debug_on_exit (specpdl + count, true);
335 call_debugger (list1 (code));
338 /* NOTE!!! Every function that can call EVAL must protect its args
339 and temporaries from garbage collection while it needs them.
340 The definition of `For' shows what you have to do. */
342 DEFUN ("or", For, Sor, 0, UNEVALLED, 0,
343 doc: /* Eval args until one of them yields non-nil, then return that value.
344 The remaining args are not evalled at all.
345 If all args return nil, return nil.
346 usage: (or CONDITIONS...) */)
347 (Lisp_Object args)
349 register Lisp_Object val = Qnil;
350 struct gcpro gcpro1;
352 GCPRO1 (args);
354 while (CONSP (args))
356 val = eval_sub (XCAR (args));
357 if (!NILP (val))
358 break;
359 args = XCDR (args);
362 UNGCPRO;
363 return val;
366 DEFUN ("and", Fand, Sand, 0, UNEVALLED, 0,
367 doc: /* Eval args until one of them yields nil, then return nil.
368 The remaining args are not evalled at all.
369 If no arg yields nil, return the last arg's value.
370 usage: (and CONDITIONS...) */)
371 (Lisp_Object args)
373 register Lisp_Object val = Qt;
374 struct gcpro gcpro1;
376 GCPRO1 (args);
378 while (CONSP (args))
380 val = eval_sub (XCAR (args));
381 if (NILP (val))
382 break;
383 args = XCDR (args);
386 UNGCPRO;
387 return val;
390 DEFUN ("if", Fif, Sif, 2, UNEVALLED, 0,
391 doc: /* If COND yields non-nil, do THEN, else do ELSE...
392 Returns the value of THEN or the value of the last of the ELSE's.
393 THEN must be one expression, but ELSE... can be zero or more expressions.
394 If COND yields nil, and there are no ELSE's, the value is nil.
395 usage: (if COND THEN ELSE...) */)
396 (Lisp_Object args)
398 Lisp_Object cond;
399 struct gcpro gcpro1;
401 GCPRO1 (args);
402 cond = eval_sub (XCAR (args));
403 UNGCPRO;
405 if (!NILP (cond))
406 return eval_sub (Fcar (XCDR (args)));
407 return Fprogn (XCDR (XCDR (args)));
410 DEFUN ("cond", Fcond, Scond, 0, UNEVALLED, 0,
411 doc: /* Try each clause until one succeeds.
412 Each clause looks like (CONDITION BODY...). CONDITION is evaluated
413 and, if the value is non-nil, this clause succeeds:
414 then the expressions in BODY are evaluated and the last one's
415 value is the value of the cond-form.
416 If a clause has one element, as in (CONDITION), then the cond-form
417 returns CONDITION's value, if that is non-nil.
418 If no clause succeeds, cond returns nil.
419 usage: (cond CLAUSES...) */)
420 (Lisp_Object args)
422 Lisp_Object val = args;
423 struct gcpro gcpro1;
425 GCPRO1 (args);
426 while (CONSP (args))
428 Lisp_Object clause = XCAR (args);
429 val = eval_sub (Fcar (clause));
430 if (!NILP (val))
432 if (!NILP (XCDR (clause)))
433 val = Fprogn (XCDR (clause));
434 break;
436 args = XCDR (args);
438 UNGCPRO;
440 return val;
443 DEFUN ("progn", Fprogn, Sprogn, 0, UNEVALLED, 0,
444 doc: /* Eval BODY forms sequentially and return value of last one.
445 usage: (progn BODY...) */)
446 (Lisp_Object body)
448 Lisp_Object val = Qnil;
449 struct gcpro gcpro1;
451 GCPRO1 (body);
453 while (CONSP (body))
455 val = eval_sub (XCAR (body));
456 body = XCDR (body);
459 UNGCPRO;
460 return val;
463 /* Evaluate BODY sequentially, discarding its value. Suitable for
464 record_unwind_protect. */
466 void
467 unwind_body (Lisp_Object body)
469 Fprogn (body);
472 DEFUN ("prog1", Fprog1, Sprog1, 1, UNEVALLED, 0,
473 doc: /* Eval FIRST and BODY sequentially; return value from FIRST.
474 The value of FIRST is saved during the evaluation of the remaining args,
475 whose values are discarded.
476 usage: (prog1 FIRST BODY...) */)
477 (Lisp_Object args)
479 Lisp_Object val;
480 Lisp_Object args_left;
481 struct gcpro gcpro1, gcpro2;
483 args_left = args;
484 val = args;
485 GCPRO2 (args, val);
487 val = eval_sub (XCAR (args_left));
488 while (CONSP (args_left = XCDR (args_left)))
489 eval_sub (XCAR (args_left));
491 UNGCPRO;
492 return val;
495 DEFUN ("prog2", Fprog2, Sprog2, 2, UNEVALLED, 0,
496 doc: /* Eval FORM1, FORM2 and BODY sequentially; return value from FORM2.
497 The value of FORM2 is saved during the evaluation of the
498 remaining args, whose values are discarded.
499 usage: (prog2 FORM1 FORM2 BODY...) */)
500 (Lisp_Object args)
502 struct gcpro gcpro1;
504 GCPRO1 (args);
505 eval_sub (XCAR (args));
506 UNGCPRO;
507 return Fprog1 (XCDR (args));
510 DEFUN ("setq", Fsetq, Ssetq, 0, UNEVALLED, 0,
511 doc: /* Set each SYM to the value of its VAL.
512 The symbols SYM are variables; they are literal (not evaluated).
513 The values VAL are expressions; they are evaluated.
514 Thus, (setq x (1+ y)) sets `x' to the value of `(1+ y)'.
515 The second VAL is not computed until after the first SYM is set, and so on;
516 each VAL can use the new value of variables set earlier in the `setq'.
517 The return value of the `setq' form is the value of the last VAL.
518 usage: (setq [SYM VAL]...) */)
519 (Lisp_Object args)
521 Lisp_Object val, sym, lex_binding;
523 val = args;
524 if (CONSP (args))
526 Lisp_Object args_left = args;
527 struct gcpro gcpro1;
528 GCPRO1 (args);
532 val = eval_sub (Fcar (XCDR (args_left)));
533 sym = XCAR (args_left);
535 /* Like for eval_sub, we do not check declared_special here since
536 it's been done when let-binding. */
537 if (!NILP (Vinternal_interpreter_environment) /* Mere optimization! */
538 && SYMBOLP (sym)
539 && !NILP (lex_binding
540 = Fassq (sym, Vinternal_interpreter_environment)))
541 XSETCDR (lex_binding, val); /* SYM is lexically bound. */
542 else
543 Fset (sym, val); /* SYM is dynamically bound. */
545 args_left = Fcdr (XCDR (args_left));
547 while (CONSP (args_left));
549 UNGCPRO;
552 return val;
555 DEFUN ("quote", Fquote, Squote, 1, UNEVALLED, 0,
556 doc: /* Return the argument, without evaluating it. `(quote x)' yields `x'.
557 Warning: `quote' does not construct its return value, but just returns
558 the value that was pre-constructed by the Lisp reader (see info node
559 `(elisp)Printed Representation').
560 This means that '(a . b) is not identical to (cons 'a 'b): the former
561 does not cons. Quoting should be reserved for constants that will
562 never be modified by side-effects, unless you like self-modifying code.
563 See the common pitfall in info node `(elisp)Rearrangement' for an example
564 of unexpected results when a quoted object is modified.
565 usage: (quote ARG) */)
566 (Lisp_Object args)
568 if (CONSP (XCDR (args)))
569 xsignal2 (Qwrong_number_of_arguments, Qquote, Flength (args));
570 return XCAR (args);
573 DEFUN ("function", Ffunction, Sfunction, 1, UNEVALLED, 0,
574 doc: /* Like `quote', but preferred for objects which are functions.
575 In byte compilation, `function' causes its argument to be compiled.
576 `quote' cannot do that.
577 usage: (function ARG) */)
578 (Lisp_Object args)
580 Lisp_Object quoted = XCAR (args);
582 if (CONSP (XCDR (args)))
583 xsignal2 (Qwrong_number_of_arguments, Qfunction, Flength (args));
585 if (!NILP (Vinternal_interpreter_environment)
586 && CONSP (quoted)
587 && EQ (XCAR (quoted), Qlambda))
588 /* This is a lambda expression within a lexical environment;
589 return an interpreted closure instead of a simple lambda. */
590 return Fcons (Qclosure, Fcons (Vinternal_interpreter_environment,
591 XCDR (quoted)));
592 else
593 /* Simply quote the argument. */
594 return quoted;
598 DEFUN ("defvaralias", Fdefvaralias, Sdefvaralias, 2, 3, 0,
599 doc: /* Make NEW-ALIAS a variable alias for symbol BASE-VARIABLE.
600 Aliased variables always have the same value; setting one sets the other.
601 Third arg DOCSTRING, if non-nil, is documentation for NEW-ALIAS. If it is
602 omitted or nil, NEW-ALIAS gets the documentation string of BASE-VARIABLE,
603 or of the variable at the end of the chain of aliases, if BASE-VARIABLE is
604 itself an alias. If NEW-ALIAS is bound, and BASE-VARIABLE is not,
605 then the value of BASE-VARIABLE is set to that of NEW-ALIAS.
606 The return value is BASE-VARIABLE. */)
607 (Lisp_Object new_alias, Lisp_Object base_variable, Lisp_Object docstring)
609 struct Lisp_Symbol *sym;
611 CHECK_SYMBOL (new_alias);
612 CHECK_SYMBOL (base_variable);
614 sym = XSYMBOL (new_alias);
616 if (sym->constant)
617 /* Not sure why, but why not? */
618 error ("Cannot make a constant an alias");
620 switch (sym->redirect)
622 case SYMBOL_FORWARDED:
623 error ("Cannot make an internal variable an alias");
624 case SYMBOL_LOCALIZED:
625 error ("Don't know how to make a localized variable an alias");
628 /* http://lists.gnu.org/archive/html/emacs-devel/2008-04/msg00834.html
629 If n_a is bound, but b_v is not, set the value of b_v to n_a,
630 so that old-code that affects n_a before the aliasing is setup
631 still works. */
632 if (NILP (Fboundp (base_variable)))
633 set_internal (base_variable, find_symbol_value (new_alias), Qnil, 1);
636 union specbinding *p;
638 for (p = specpdl_ptr; p > specpdl; )
639 if ((--p)->kind >= SPECPDL_LET
640 && (EQ (new_alias, specpdl_symbol (p))))
641 error ("Don't know how to make a let-bound variable an alias");
644 sym->declared_special = 1;
645 XSYMBOL (base_variable)->declared_special = 1;
646 sym->redirect = SYMBOL_VARALIAS;
647 SET_SYMBOL_ALIAS (sym, XSYMBOL (base_variable));
648 sym->constant = SYMBOL_CONSTANT_P (base_variable);
649 LOADHIST_ATTACH (new_alias);
650 /* Even if docstring is nil: remove old docstring. */
651 Fput (new_alias, Qvariable_documentation, docstring);
653 return base_variable;
656 static union specbinding *
657 default_toplevel_binding (Lisp_Object symbol)
659 union specbinding *binding = NULL;
660 union specbinding *pdl = specpdl_ptr;
661 while (pdl > specpdl)
663 switch ((--pdl)->kind)
665 case SPECPDL_LET_DEFAULT:
666 case SPECPDL_LET:
667 if (EQ (specpdl_symbol (pdl), symbol))
668 binding = pdl;
669 break;
672 return binding;
675 DEFUN ("default-toplevel-value", Fdefault_toplevel_value, Sdefault_toplevel_value, 1, 1, 0,
676 doc: /* Return SYMBOL's toplevel default value.
677 "Toplevel" means outside of any let binding. */)
678 (Lisp_Object symbol)
680 union specbinding *binding = default_toplevel_binding (symbol);
681 Lisp_Object value
682 = binding ? specpdl_old_value (binding) : Fdefault_value (symbol);
683 if (!EQ (value, Qunbound))
684 return value;
685 xsignal1 (Qvoid_variable, symbol);
688 DEFUN ("set-default-toplevel-value", Fset_default_toplevel_value,
689 Sset_default_toplevel_value, 2, 2, 0,
690 doc: /* Set SYMBOL's toplevel default value to VALUE.
691 "Toplevel" means outside of any let binding. */)
692 (Lisp_Object symbol, Lisp_Object value)
694 union specbinding *binding = default_toplevel_binding (symbol);
695 if (binding)
696 set_specpdl_old_value (binding, value);
697 else
698 Fset_default (symbol, value);
699 return Qnil;
702 DEFUN ("defvar", Fdefvar, Sdefvar, 1, UNEVALLED, 0,
703 doc: /* Define SYMBOL as a variable, and return SYMBOL.
704 You are not required to define a variable in order to use it, but
705 defining it lets you supply an initial value and documentation, which
706 can be referred to by the Emacs help facilities and other programming
707 tools. The `defvar' form also declares the variable as \"special\",
708 so that it is always dynamically bound even if `lexical-binding' is t.
710 The optional argument INITVALUE is evaluated, and used to set SYMBOL,
711 only if SYMBOL's value is void. If SYMBOL is buffer-local, its
712 default value is what is set; buffer-local values are not affected.
713 If INITVALUE is missing, SYMBOL's value is not set.
715 If SYMBOL has a local binding, then this form affects the local
716 binding. This is usually not what you want. Thus, if you need to
717 load a file defining variables, with this form or with `defconst' or
718 `defcustom', you should always load that file _outside_ any bindings
719 for these variables. \(`defconst' and `defcustom' behave similarly in
720 this respect.)
722 The optional argument DOCSTRING is a documentation string for the
723 variable.
725 To define a user option, use `defcustom' instead of `defvar'.
726 usage: (defvar SYMBOL &optional INITVALUE DOCSTRING) */)
727 (Lisp_Object args)
729 Lisp_Object sym, tem, tail;
731 sym = XCAR (args);
732 tail = XCDR (args);
734 if (CONSP (tail))
736 if (CONSP (XCDR (tail)) && CONSP (XCDR (XCDR (tail))))
737 error ("Too many arguments");
739 tem = Fdefault_boundp (sym);
741 /* Do it before evaluating the initial value, for self-references. */
742 XSYMBOL (sym)->declared_special = 1;
744 if (NILP (tem))
745 Fset_default (sym, eval_sub (XCAR (tail)));
746 else
747 { /* Check if there is really a global binding rather than just a let
748 binding that shadows the global unboundness of the var. */
749 union specbinding *binding = default_toplevel_binding (sym);
750 if (binding && EQ (specpdl_old_value (binding), Qunbound))
752 set_specpdl_old_value (binding, eval_sub (XCAR (tail)));
755 tail = XCDR (tail);
756 tem = Fcar (tail);
757 if (!NILP (tem))
759 if (!NILP (Vpurify_flag))
760 tem = Fpurecopy (tem);
761 Fput (sym, Qvariable_documentation, tem);
763 LOADHIST_ATTACH (sym);
765 else if (!NILP (Vinternal_interpreter_environment)
766 && !XSYMBOL (sym)->declared_special)
767 /* A simple (defvar foo) with lexical scoping does "nothing" except
768 declare that var to be dynamically scoped *locally* (i.e. within
769 the current file or let-block). */
770 Vinternal_interpreter_environment
771 = Fcons (sym, Vinternal_interpreter_environment);
772 else
774 /* Simple (defvar <var>) should not count as a definition at all.
775 It could get in the way of other definitions, and unloading this
776 package could try to make the variable unbound. */
779 return sym;
782 DEFUN ("defconst", Fdefconst, Sdefconst, 2, UNEVALLED, 0,
783 doc: /* Define SYMBOL as a constant variable.
784 This declares that neither programs nor users should ever change the
785 value. This constancy is not actually enforced by Emacs Lisp, but
786 SYMBOL is marked as a special variable so that it is never lexically
787 bound.
789 The `defconst' form always sets the value of SYMBOL to the result of
790 evalling INITVALUE. If SYMBOL is buffer-local, its default value is
791 what is set; buffer-local values are not affected. If SYMBOL has a
792 local binding, then this form sets the local binding's value.
793 However, you should normally not make local bindings for variables
794 defined with this form.
796 The optional DOCSTRING specifies the variable's documentation string.
797 usage: (defconst SYMBOL INITVALUE [DOCSTRING]) */)
798 (Lisp_Object args)
800 Lisp_Object sym, tem;
802 sym = XCAR (args);
803 if (CONSP (Fcdr (XCDR (XCDR (args)))))
804 error ("Too many arguments");
806 tem = eval_sub (Fcar (XCDR (args)));
807 if (!NILP (Vpurify_flag))
808 tem = Fpurecopy (tem);
809 Fset_default (sym, tem);
810 XSYMBOL (sym)->declared_special = 1;
811 tem = Fcar (XCDR (XCDR (args)));
812 if (!NILP (tem))
814 if (!NILP (Vpurify_flag))
815 tem = Fpurecopy (tem);
816 Fput (sym, Qvariable_documentation, tem);
818 Fput (sym, Qrisky_local_variable, Qt);
819 LOADHIST_ATTACH (sym);
820 return sym;
823 /* Make SYMBOL lexically scoped. */
824 DEFUN ("internal-make-var-non-special", Fmake_var_non_special,
825 Smake_var_non_special, 1, 1, 0,
826 doc: /* Internal function. */)
827 (Lisp_Object symbol)
829 CHECK_SYMBOL (symbol);
830 XSYMBOL (symbol)->declared_special = 0;
831 return Qnil;
835 DEFUN ("let*", FletX, SletX, 1, UNEVALLED, 0,
836 doc: /* Bind variables according to VARLIST then eval BODY.
837 The value of the last form in BODY is returned.
838 Each element of VARLIST is a symbol (which is bound to nil)
839 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
840 Each VALUEFORM can refer to the symbols already bound by this VARLIST.
841 usage: (let* VARLIST BODY...) */)
842 (Lisp_Object args)
844 Lisp_Object varlist, var, val, elt, lexenv;
845 ptrdiff_t count = SPECPDL_INDEX ();
846 struct gcpro gcpro1, gcpro2, gcpro3;
848 GCPRO3 (args, elt, varlist);
850 lexenv = Vinternal_interpreter_environment;
852 varlist = XCAR (args);
853 while (CONSP (varlist))
855 QUIT;
857 elt = XCAR (varlist);
858 if (SYMBOLP (elt))
860 var = elt;
861 val = Qnil;
863 else if (! NILP (Fcdr (Fcdr (elt))))
864 signal_error ("`let' bindings can have only one value-form", elt);
865 else
867 var = Fcar (elt);
868 val = eval_sub (Fcar (Fcdr (elt)));
871 if (!NILP (lexenv) && SYMBOLP (var)
872 && !XSYMBOL (var)->declared_special
873 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
874 /* Lexically bind VAR by adding it to the interpreter's binding
875 alist. */
877 Lisp_Object newenv
878 = Fcons (Fcons (var, val), Vinternal_interpreter_environment);
879 if (EQ (Vinternal_interpreter_environment, lexenv))
880 /* Save the old lexical environment on the specpdl stack,
881 but only for the first lexical binding, since we'll never
882 need to revert to one of the intermediate ones. */
883 specbind (Qinternal_interpreter_environment, newenv);
884 else
885 Vinternal_interpreter_environment = newenv;
887 else
888 specbind (var, val);
890 varlist = XCDR (varlist);
892 UNGCPRO;
893 val = Fprogn (XCDR (args));
894 return unbind_to (count, val);
897 DEFUN ("let", Flet, Slet, 1, UNEVALLED, 0,
898 doc: /* Bind variables according to VARLIST then eval BODY.
899 The value of the last form in BODY is returned.
900 Each element of VARLIST is a symbol (which is bound to nil)
901 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
902 All the VALUEFORMs are evalled before any symbols are bound.
903 usage: (let VARLIST BODY...) */)
904 (Lisp_Object args)
906 Lisp_Object *temps, tem, lexenv;
907 register Lisp_Object elt, varlist;
908 ptrdiff_t count = SPECPDL_INDEX ();
909 ptrdiff_t argnum;
910 struct gcpro gcpro1, gcpro2;
911 USE_SAFE_ALLOCA;
913 varlist = XCAR (args);
915 /* Make space to hold the values to give the bound variables. */
916 elt = Flength (varlist);
917 SAFE_ALLOCA_LISP (temps, XFASTINT (elt));
919 /* Compute the values and store them in `temps'. */
921 GCPRO2 (args, *temps);
922 gcpro2.nvars = 0;
924 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
926 QUIT;
927 elt = XCAR (varlist);
928 if (SYMBOLP (elt))
929 temps [argnum++] = Qnil;
930 else if (! NILP (Fcdr (Fcdr (elt))))
931 signal_error ("`let' bindings can have only one value-form", elt);
932 else
933 temps [argnum++] = eval_sub (Fcar (Fcdr (elt)));
934 gcpro2.nvars = argnum;
936 UNGCPRO;
938 lexenv = Vinternal_interpreter_environment;
940 varlist = XCAR (args);
941 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
943 Lisp_Object var;
945 elt = XCAR (varlist);
946 var = SYMBOLP (elt) ? elt : Fcar (elt);
947 tem = temps[argnum++];
949 if (!NILP (lexenv) && SYMBOLP (var)
950 && !XSYMBOL (var)->declared_special
951 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
952 /* Lexically bind VAR by adding it to the lexenv alist. */
953 lexenv = Fcons (Fcons (var, tem), lexenv);
954 else
955 /* Dynamically bind VAR. */
956 specbind (var, tem);
959 if (!EQ (lexenv, Vinternal_interpreter_environment))
960 /* Instantiate a new lexical environment. */
961 specbind (Qinternal_interpreter_environment, lexenv);
963 elt = Fprogn (XCDR (args));
964 SAFE_FREE ();
965 return unbind_to (count, elt);
968 DEFUN ("while", Fwhile, Swhile, 1, UNEVALLED, 0,
969 doc: /* If TEST yields non-nil, eval BODY... and repeat.
970 The order of execution is thus TEST, BODY, TEST, BODY and so on
971 until TEST returns nil.
972 usage: (while TEST BODY...) */)
973 (Lisp_Object args)
975 Lisp_Object test, body;
976 struct gcpro gcpro1, gcpro2;
978 GCPRO2 (test, body);
980 test = XCAR (args);
981 body = XCDR (args);
982 while (!NILP (eval_sub (test)))
984 QUIT;
985 Fprogn (body);
988 UNGCPRO;
989 return Qnil;
992 DEFUN ("macroexpand", Fmacroexpand, Smacroexpand, 1, 2, 0,
993 doc: /* Return result of expanding macros at top level of FORM.
994 If FORM is not a macro call, it is returned unchanged.
995 Otherwise, the macro is expanded and the expansion is considered
996 in place of FORM. When a non-macro-call results, it is returned.
998 The second optional arg ENVIRONMENT specifies an environment of macro
999 definitions to shadow the loaded ones for use in file byte-compilation. */)
1000 (Lisp_Object form, Lisp_Object environment)
1002 /* With cleanups from Hallvard Furuseth. */
1003 register Lisp_Object expander, sym, def, tem;
1005 while (1)
1007 /* Come back here each time we expand a macro call,
1008 in case it expands into another macro call. */
1009 if (!CONSP (form))
1010 break;
1011 /* Set SYM, give DEF and TEM right values in case SYM is not a symbol. */
1012 def = sym = XCAR (form);
1013 tem = Qnil;
1014 /* Trace symbols aliases to other symbols
1015 until we get a symbol that is not an alias. */
1016 while (SYMBOLP (def))
1018 QUIT;
1019 sym = def;
1020 tem = Fassq (sym, environment);
1021 if (NILP (tem))
1023 def = XSYMBOL (sym)->function;
1024 if (!NILP (def))
1025 continue;
1027 break;
1029 /* Right now TEM is the result from SYM in ENVIRONMENT,
1030 and if TEM is nil then DEF is SYM's function definition. */
1031 if (NILP (tem))
1033 /* SYM is not mentioned in ENVIRONMENT.
1034 Look at its function definition. */
1035 struct gcpro gcpro1;
1036 GCPRO1 (form);
1037 def = Fautoload_do_load (def, sym, Qmacro);
1038 UNGCPRO;
1039 if (!CONSP (def))
1040 /* Not defined or definition not suitable. */
1041 break;
1042 if (!EQ (XCAR (def), Qmacro))
1043 break;
1044 else expander = XCDR (def);
1046 else
1048 expander = XCDR (tem);
1049 if (NILP (expander))
1050 break;
1053 Lisp_Object newform = apply1 (expander, XCDR (form));
1054 if (EQ (form, newform))
1055 break;
1056 else
1057 form = newform;
1060 return form;
1063 DEFUN ("catch", Fcatch, Scatch, 1, UNEVALLED, 0,
1064 doc: /* Eval BODY allowing nonlocal exits using `throw'.
1065 TAG is evalled to get the tag to use; it must not be nil.
1067 Then the BODY is executed.
1068 Within BODY, a call to `throw' with the same TAG exits BODY and this `catch'.
1069 If no throw happens, `catch' returns the value of the last BODY form.
1070 If a throw happens, it specifies the value to return from `catch'.
1071 usage: (catch TAG BODY...) */)
1072 (Lisp_Object args)
1074 register Lisp_Object tag;
1075 struct gcpro gcpro1;
1077 GCPRO1 (args);
1078 tag = eval_sub (XCAR (args));
1079 UNGCPRO;
1080 return internal_catch (tag, Fprogn, XCDR (args));
1083 /* Assert that E is true, as a comment only. Use this instead of
1084 eassert (E) when E contains variables that might be clobbered by a
1085 longjmp. */
1087 #define clobbered_eassert(E) ((void) 0)
1089 /* Set up a catch, then call C function FUNC on argument ARG.
1090 FUNC should return a Lisp_Object.
1091 This is how catches are done from within C code. */
1093 Lisp_Object
1094 internal_catch (Lisp_Object tag, Lisp_Object (*func) (Lisp_Object), Lisp_Object arg)
1096 /* This structure is made part of the chain `catchlist'. */
1097 struct handler *c;
1099 /* Fill in the components of c, and put it on the list. */
1100 PUSH_HANDLER (c, tag, CATCHER);
1102 /* Call FUNC. */
1103 if (! sys_setjmp (c->jmp))
1105 Lisp_Object val = (*func) (arg);
1106 clobbered_eassert (handlerlist == c);
1107 handlerlist = handlerlist->next;
1108 return val;
1110 else
1111 { /* Throw works by a longjmp that comes right here. */
1112 Lisp_Object val = handlerlist->val;
1113 clobbered_eassert (handlerlist == c);
1114 handlerlist = handlerlist->next;
1115 return val;
1119 /* Unwind the specbind, catch, and handler stacks back to CATCH, and
1120 jump to that CATCH, returning VALUE as the value of that catch.
1122 This is the guts of Fthrow and Fsignal; they differ only in the way
1123 they choose the catch tag to throw to. A catch tag for a
1124 condition-case form has a TAG of Qnil.
1126 Before each catch is discarded, unbind all special bindings and
1127 execute all unwind-protect clauses made above that catch. Unwind
1128 the handler stack as we go, so that the proper handlers are in
1129 effect for each unwind-protect clause we run. At the end, restore
1130 some static info saved in CATCH, and longjmp to the location
1131 specified there.
1133 This is used for correct unwinding in Fthrow and Fsignal. */
1135 static _Noreturn void
1136 unwind_to_catch (struct handler *catch, Lisp_Object value)
1138 bool last_time;
1140 eassert (catch->next);
1142 /* Save the value in the tag. */
1143 catch->val = value;
1145 /* Restore certain special C variables. */
1146 set_poll_suppress_count (catch->poll_suppress_count);
1147 unblock_input_to (catch->interrupt_input_blocked);
1148 immediate_quit = 0;
1152 /* Unwind the specpdl stack, and then restore the proper set of
1153 handlers. */
1154 unbind_to (handlerlist->pdlcount, Qnil);
1155 last_time = handlerlist == catch;
1156 if (! last_time)
1157 handlerlist = handlerlist->next;
1159 while (! last_time);
1161 eassert (handlerlist == catch);
1163 byte_stack_list = catch->byte_stack;
1164 gcprolist = catch->gcpro;
1165 #ifdef DEBUG_GCPRO
1166 gcpro_level = gcprolist ? gcprolist->level + 1 : 0;
1167 #endif
1168 lisp_eval_depth = catch->lisp_eval_depth;
1170 sys_longjmp (catch->jmp, 1);
1173 DEFUN ("throw", Fthrow, Sthrow, 2, 2, 0,
1174 doc: /* Throw to the catch for TAG and return VALUE from it.
1175 Both TAG and VALUE are evalled. */)
1176 (register Lisp_Object tag, Lisp_Object value)
1178 struct handler *c;
1180 if (!NILP (tag))
1181 for (c = handlerlist; c; c = c->next)
1183 if (c->type == CATCHER && EQ (c->tag_or_ch, tag))
1184 unwind_to_catch (c, value);
1186 xsignal2 (Qno_catch, tag, value);
1190 DEFUN ("unwind-protect", Funwind_protect, Sunwind_protect, 1, UNEVALLED, 0,
1191 doc: /* Do BODYFORM, protecting with UNWINDFORMS.
1192 If BODYFORM completes normally, its value is returned
1193 after executing the UNWINDFORMS.
1194 If BODYFORM exits nonlocally, the UNWINDFORMS are executed anyway.
1195 usage: (unwind-protect BODYFORM UNWINDFORMS...) */)
1196 (Lisp_Object args)
1198 Lisp_Object val;
1199 ptrdiff_t count = SPECPDL_INDEX ();
1201 record_unwind_protect (unwind_body, XCDR (args));
1202 val = eval_sub (XCAR (args));
1203 return unbind_to (count, val);
1206 DEFUN ("condition-case", Fcondition_case, Scondition_case, 2, UNEVALLED, 0,
1207 doc: /* Regain control when an error is signaled.
1208 Executes BODYFORM and returns its value if no error happens.
1209 Each element of HANDLERS looks like (CONDITION-NAME BODY...)
1210 where the BODY is made of Lisp expressions.
1212 A handler is applicable to an error
1213 if CONDITION-NAME is one of the error's condition names.
1214 If an error happens, the first applicable handler is run.
1216 The car of a handler may be a list of condition names instead of a
1217 single condition name; then it handles all of them. If the special
1218 condition name `debug' is present in this list, it allows another
1219 condition in the list to run the debugger if `debug-on-error' and the
1220 other usual mechanisms says it should (otherwise, `condition-case'
1221 suppresses the debugger).
1223 When a handler handles an error, control returns to the `condition-case'
1224 and it executes the handler's BODY...
1225 with VAR bound to (ERROR-SYMBOL . SIGNAL-DATA) from the error.
1226 \(If VAR is nil, the handler can't access that information.)
1227 Then the value of the last BODY form is returned from the `condition-case'
1228 expression.
1230 See also the function `signal' for more info.
1231 usage: (condition-case VAR BODYFORM &rest HANDLERS) */)
1232 (Lisp_Object args)
1234 Lisp_Object var = XCAR (args);
1235 Lisp_Object bodyform = XCAR (XCDR (args));
1236 Lisp_Object handlers = XCDR (XCDR (args));
1238 return internal_lisp_condition_case (var, bodyform, handlers);
1241 /* Like Fcondition_case, but the args are separate
1242 rather than passed in a list. Used by Fbyte_code. */
1244 Lisp_Object
1245 internal_lisp_condition_case (volatile Lisp_Object var, Lisp_Object bodyform,
1246 Lisp_Object handlers)
1248 Lisp_Object val;
1249 struct handler *c;
1250 struct handler *oldhandlerlist = handlerlist;
1251 int clausenb = 0;
1253 CHECK_SYMBOL (var);
1255 for (val = handlers; CONSP (val); val = XCDR (val))
1257 Lisp_Object tem = XCAR (val);
1258 clausenb++;
1259 if (! (NILP (tem)
1260 || (CONSP (tem)
1261 && (SYMBOLP (XCAR (tem))
1262 || CONSP (XCAR (tem))))))
1263 error ("Invalid condition handler: %s",
1264 SDATA (Fprin1_to_string (tem, Qt)));
1267 { /* The first clause is the one that should be checked first, so it should
1268 be added to handlerlist last. So we build in `clauses' a table that
1269 contains `handlers' but in reverse order. SAFE_ALLOCA won't work
1270 here due to the setjmp, so impose a MAX_ALLOCA limit. */
1271 if (MAX_ALLOCA / word_size < clausenb)
1272 memory_full (SIZE_MAX);
1273 Lisp_Object *clauses = alloca (clausenb * sizeof *clauses);
1274 Lisp_Object *volatile clauses_volatile = clauses;
1275 int i = clausenb;
1276 for (val = handlers; CONSP (val); val = XCDR (val))
1277 clauses[--i] = XCAR (val);
1278 for (i = 0; i < clausenb; i++)
1280 Lisp_Object clause = clauses[i];
1281 Lisp_Object condition = XCAR (clause);
1282 if (!CONSP (condition))
1283 condition = Fcons (condition, Qnil);
1284 PUSH_HANDLER (c, condition, CONDITION_CASE);
1285 if (sys_setjmp (c->jmp))
1287 ptrdiff_t count = SPECPDL_INDEX ();
1288 Lisp_Object val = handlerlist->val;
1289 Lisp_Object *chosen_clause = clauses_volatile;
1290 for (c = handlerlist->next; c != oldhandlerlist; c = c->next)
1291 chosen_clause++;
1292 handlerlist = oldhandlerlist;
1293 if (!NILP (var))
1295 if (!NILP (Vinternal_interpreter_environment))
1296 specbind (Qinternal_interpreter_environment,
1297 Fcons (Fcons (var, val),
1298 Vinternal_interpreter_environment));
1299 else
1300 specbind (var, val);
1302 val = Fprogn (XCDR (*chosen_clause));
1303 /* Note that this just undoes the binding of var; whoever
1304 longjumped to us unwound the stack to c.pdlcount before
1305 throwing. */
1306 if (!NILP (var))
1307 unbind_to (count, Qnil);
1308 return val;
1313 val = eval_sub (bodyform);
1314 handlerlist = oldhandlerlist;
1315 return val;
1318 /* Call the function BFUN with no arguments, catching errors within it
1319 according to HANDLERS. If there is an error, call HFUN with
1320 one argument which is the data that describes the error:
1321 (SIGNALNAME . DATA)
1323 HANDLERS can be a list of conditions to catch.
1324 If HANDLERS is Qt, catch all errors.
1325 If HANDLERS is Qerror, catch all errors
1326 but allow the debugger to run if that is enabled. */
1328 Lisp_Object
1329 internal_condition_case (Lisp_Object (*bfun) (void), Lisp_Object handlers,
1330 Lisp_Object (*hfun) (Lisp_Object))
1332 Lisp_Object val;
1333 struct handler *c;
1335 PUSH_HANDLER (c, handlers, CONDITION_CASE);
1336 if (sys_setjmp (c->jmp))
1338 Lisp_Object val = handlerlist->val;
1339 clobbered_eassert (handlerlist == c);
1340 handlerlist = handlerlist->next;
1341 return (*hfun) (val);
1344 val = (*bfun) ();
1345 clobbered_eassert (handlerlist == c);
1346 handlerlist = handlerlist->next;
1347 return val;
1350 /* Like internal_condition_case but call BFUN with ARG as its argument. */
1352 Lisp_Object
1353 internal_condition_case_1 (Lisp_Object (*bfun) (Lisp_Object), Lisp_Object arg,
1354 Lisp_Object handlers, Lisp_Object (*hfun) (Lisp_Object))
1356 Lisp_Object val;
1357 struct handler *c;
1359 PUSH_HANDLER (c, handlers, CONDITION_CASE);
1360 if (sys_setjmp (c->jmp))
1362 Lisp_Object val = handlerlist->val;
1363 clobbered_eassert (handlerlist == c);
1364 handlerlist = handlerlist->next;
1365 return (*hfun) (val);
1368 val = (*bfun) (arg);
1369 clobbered_eassert (handlerlist == c);
1370 handlerlist = handlerlist->next;
1371 return val;
1374 /* Like internal_condition_case_1 but call BFUN with ARG1 and ARG2 as
1375 its arguments. */
1377 Lisp_Object
1378 internal_condition_case_2 (Lisp_Object (*bfun) (Lisp_Object, Lisp_Object),
1379 Lisp_Object arg1,
1380 Lisp_Object arg2,
1381 Lisp_Object handlers,
1382 Lisp_Object (*hfun) (Lisp_Object))
1384 Lisp_Object val;
1385 struct handler *c;
1387 PUSH_HANDLER (c, 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);
1396 val = (*bfun) (arg1, arg2);
1397 clobbered_eassert (handlerlist == c);
1398 handlerlist = handlerlist->next;
1399 return val;
1402 /* Like internal_condition_case but call BFUN with NARGS as first,
1403 and ARGS as second argument. */
1405 Lisp_Object
1406 internal_condition_case_n (Lisp_Object (*bfun) (ptrdiff_t, Lisp_Object *),
1407 ptrdiff_t nargs,
1408 Lisp_Object *args,
1409 Lisp_Object handlers,
1410 Lisp_Object (*hfun) (Lisp_Object err,
1411 ptrdiff_t nargs,
1412 Lisp_Object *args))
1414 Lisp_Object val;
1415 struct handler *c;
1417 PUSH_HANDLER (c, handlers, CONDITION_CASE);
1418 if (sys_setjmp (c->jmp))
1420 Lisp_Object val = handlerlist->val;
1421 clobbered_eassert (handlerlist == c);
1422 handlerlist = handlerlist->next;
1423 return (*hfun) (val, nargs, args);
1426 val = (*bfun) (nargs, args);
1427 clobbered_eassert (handlerlist == c);
1428 handlerlist = handlerlist->next;
1429 return val;
1433 static Lisp_Object find_handler_clause (Lisp_Object, Lisp_Object);
1434 static bool maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig,
1435 Lisp_Object data);
1437 void
1438 process_quit_flag (void)
1440 Lisp_Object flag = Vquit_flag;
1441 Vquit_flag = Qnil;
1442 if (EQ (flag, Qkill_emacs))
1443 Fkill_emacs (Qnil);
1444 if (EQ (Vthrow_on_input, flag))
1445 Fthrow (Vthrow_on_input, Qt);
1446 Fsignal (Qquit, Qnil);
1449 DEFUN ("signal", Fsignal, Ssignal, 2, 2, 0,
1450 doc: /* Signal an error. Args are ERROR-SYMBOL and associated DATA.
1451 This function does not return.
1453 An error symbol is a symbol with an `error-conditions' property
1454 that is a list of condition names.
1455 A handler for any of those names will get to handle this signal.
1456 The symbol `error' should normally be one of them.
1458 DATA should be a list. Its elements are printed as part of the error message.
1459 See Info anchor `(elisp)Definition of signal' for some details on how this
1460 error message is constructed.
1461 If the signal is handled, DATA is made available to the handler.
1462 See also the function `condition-case'. */)
1463 (Lisp_Object error_symbol, Lisp_Object data)
1465 /* When memory is full, ERROR-SYMBOL is nil,
1466 and DATA is (REAL-ERROR-SYMBOL . REAL-DATA).
1467 That is a special case--don't do this in other situations. */
1468 Lisp_Object conditions;
1469 Lisp_Object string;
1470 Lisp_Object real_error_symbol
1471 = (NILP (error_symbol) ? Fcar (data) : error_symbol);
1472 register Lisp_Object clause = Qnil;
1473 struct handler *h;
1475 immediate_quit = 0;
1476 abort_on_gc = 0;
1477 if (gc_in_progress || waiting_for_input)
1478 emacs_abort ();
1480 #if 0 /* rms: I don't know why this was here,
1481 but it is surely wrong for an error that is handled. */
1482 #ifdef HAVE_WINDOW_SYSTEM
1483 if (display_hourglass_p)
1484 cancel_hourglass ();
1485 #endif
1486 #endif
1488 /* This hook is used by edebug. */
1489 if (! NILP (Vsignal_hook_function)
1490 && ! NILP (error_symbol))
1492 /* Edebug takes care of restoring these variables when it exits. */
1493 if (lisp_eval_depth + 20 > max_lisp_eval_depth)
1494 max_lisp_eval_depth = lisp_eval_depth + 20;
1496 if (SPECPDL_INDEX () + 40 > max_specpdl_size)
1497 max_specpdl_size = SPECPDL_INDEX () + 40;
1499 call2 (Vsignal_hook_function, error_symbol, data);
1502 conditions = Fget (real_error_symbol, Qerror_conditions);
1504 /* Remember from where signal was called. Skip over the frame for
1505 `signal' itself. If a frame for `error' follows, skip that,
1506 too. Don't do this when ERROR_SYMBOL is nil, because that
1507 is a memory-full error. */
1508 Vsignaling_function = Qnil;
1509 if (!NILP (error_symbol))
1511 union specbinding *pdl = backtrace_next (backtrace_top ());
1512 if (backtrace_p (pdl) && EQ (backtrace_function (pdl), Qerror))
1513 pdl = backtrace_next (pdl);
1514 if (backtrace_p (pdl))
1515 Vsignaling_function = backtrace_function (pdl);
1518 for (h = handlerlist; h; h = h->next)
1520 if (h->type != CONDITION_CASE)
1521 continue;
1522 clause = find_handler_clause (h->tag_or_ch, conditions);
1523 if (!NILP (clause))
1524 break;
1527 if (/* Don't run the debugger for a memory-full error.
1528 (There is no room in memory to do that!) */
1529 !NILP (error_symbol)
1530 && (!NILP (Vdebug_on_signal)
1531 /* If no handler is present now, try to run the debugger. */
1532 || NILP (clause)
1533 /* A `debug' symbol in the handler list disables the normal
1534 suppression of the debugger. */
1535 || (CONSP (clause) && CONSP (clause)
1536 && !NILP (Fmemq (Qdebug, clause)))
1537 /* Special handler that means "print a message and run debugger
1538 if requested". */
1539 || EQ (h->tag_or_ch, Qerror)))
1541 bool debugger_called
1542 = maybe_call_debugger (conditions, error_symbol, data);
1543 /* We can't return values to code which signaled an error, but we
1544 can continue code which has signaled a quit. */
1545 if (debugger_called && EQ (real_error_symbol, Qquit))
1546 return Qnil;
1549 if (!NILP (clause))
1551 Lisp_Object unwind_data
1552 = (NILP (error_symbol) ? data : Fcons (error_symbol, data));
1554 unwind_to_catch (h, unwind_data);
1556 else
1558 if (handlerlist != &handlerlist_sentinel)
1559 /* FIXME: This will come right back here if there's no `top-level'
1560 catcher. A better solution would be to abort here, and instead
1561 add a catch-all condition handler so we never come here. */
1562 Fthrow (Qtop_level, Qt);
1565 if (! NILP (error_symbol))
1566 data = Fcons (error_symbol, data);
1568 string = Ferror_message_string (data);
1569 fatal ("%s", SDATA (string));
1572 /* Internal version of Fsignal that never returns.
1573 Used for anything but Qquit (which can return from Fsignal). */
1575 void
1576 xsignal (Lisp_Object error_symbol, Lisp_Object data)
1578 Fsignal (error_symbol, data);
1579 emacs_abort ();
1582 /* Like xsignal, but takes 0, 1, 2, or 3 args instead of a list. */
1584 void
1585 xsignal0 (Lisp_Object error_symbol)
1587 xsignal (error_symbol, Qnil);
1590 void
1591 xsignal1 (Lisp_Object error_symbol, Lisp_Object arg)
1593 xsignal (error_symbol, list1 (arg));
1596 void
1597 xsignal2 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2)
1599 xsignal (error_symbol, list2 (arg1, arg2));
1602 void
1603 xsignal3 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
1605 xsignal (error_symbol, list3 (arg1, arg2, arg3));
1608 /* Signal `error' with message S, and additional arg ARG.
1609 If ARG is not a genuine list, make it a one-element list. */
1611 void
1612 signal_error (const char *s, Lisp_Object arg)
1614 Lisp_Object tortoise, hare;
1616 hare = tortoise = arg;
1617 while (CONSP (hare))
1619 hare = XCDR (hare);
1620 if (!CONSP (hare))
1621 break;
1623 hare = XCDR (hare);
1624 tortoise = XCDR (tortoise);
1626 if (EQ (hare, tortoise))
1627 break;
1630 if (!NILP (hare))
1631 arg = list1 (arg);
1633 xsignal (Qerror, Fcons (build_string (s), arg));
1637 /* Return true if LIST is a non-nil atom or
1638 a list containing one of CONDITIONS. */
1640 static bool
1641 wants_debugger (Lisp_Object list, Lisp_Object conditions)
1643 if (NILP (list))
1644 return 0;
1645 if (! CONSP (list))
1646 return 1;
1648 while (CONSP (conditions))
1650 Lisp_Object this, tail;
1651 this = XCAR (conditions);
1652 for (tail = list; CONSP (tail); tail = XCDR (tail))
1653 if (EQ (XCAR (tail), this))
1654 return 1;
1655 conditions = XCDR (conditions);
1657 return 0;
1660 /* Return true if an error with condition-symbols CONDITIONS,
1661 and described by SIGNAL-DATA, should skip the debugger
1662 according to debugger-ignored-errors. */
1664 static bool
1665 skip_debugger (Lisp_Object conditions, Lisp_Object data)
1667 Lisp_Object tail;
1668 bool first_string = 1;
1669 Lisp_Object error_message;
1671 error_message = Qnil;
1672 for (tail = Vdebug_ignored_errors; CONSP (tail); tail = XCDR (tail))
1674 if (STRINGP (XCAR (tail)))
1676 if (first_string)
1678 error_message = Ferror_message_string (data);
1679 first_string = 0;
1682 if (fast_string_match (XCAR (tail), error_message) >= 0)
1683 return 1;
1685 else
1687 Lisp_Object contail;
1689 for (contail = conditions; CONSP (contail); contail = XCDR (contail))
1690 if (EQ (XCAR (tail), XCAR (contail)))
1691 return 1;
1695 return 0;
1698 /* Call the debugger if calling it is currently enabled for CONDITIONS.
1699 SIG and DATA describe the signal. There are two ways to pass them:
1700 = SIG is the error symbol, and DATA is the rest of the data.
1701 = SIG is nil, and DATA is (SYMBOL . REST-OF-DATA).
1702 This is for memory-full errors only. */
1703 static bool
1704 maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig, Lisp_Object data)
1706 Lisp_Object combined_data;
1708 combined_data = Fcons (sig, data);
1710 if (
1711 /* Don't try to run the debugger with interrupts blocked.
1712 The editing loop would return anyway. */
1713 ! input_blocked_p ()
1714 && NILP (Vinhibit_debugger)
1715 /* Does user want to enter debugger for this kind of error? */
1716 && (EQ (sig, Qquit)
1717 ? debug_on_quit
1718 : wants_debugger (Vdebug_on_error, conditions))
1719 && ! skip_debugger (conditions, combined_data)
1720 /* RMS: What's this for? */
1721 && when_entered_debugger < num_nonmacro_input_events)
1723 call_debugger (list2 (Qerror, combined_data));
1724 return 1;
1727 return 0;
1730 static Lisp_Object
1731 find_handler_clause (Lisp_Object handlers, Lisp_Object conditions)
1733 register Lisp_Object h;
1735 /* t is used by handlers for all conditions, set up by C code. */
1736 if (EQ (handlers, Qt))
1737 return Qt;
1739 /* error is used similarly, but means print an error message
1740 and run the debugger if that is enabled. */
1741 if (EQ (handlers, Qerror))
1742 return Qt;
1744 for (h = handlers; CONSP (h); h = XCDR (h))
1746 Lisp_Object handler = XCAR (h);
1747 if (!NILP (Fmemq (handler, conditions)))
1748 return handlers;
1751 return Qnil;
1755 /* Dump an error message; called like vprintf. */
1756 void
1757 verror (const char *m, va_list ap)
1759 char buf[4000];
1760 ptrdiff_t size = sizeof buf;
1761 ptrdiff_t size_max = STRING_BYTES_BOUND + 1;
1762 char *buffer = buf;
1763 ptrdiff_t used;
1764 Lisp_Object string;
1766 used = evxprintf (&buffer, &size, buf, size_max, m, ap);
1767 string = make_string (buffer, used);
1768 if (buffer != buf)
1769 xfree (buffer);
1771 xsignal1 (Qerror, string);
1775 /* Dump an error message; called like printf. */
1777 /* VARARGS 1 */
1778 void
1779 error (const char *m, ...)
1781 va_list ap;
1782 va_start (ap, m);
1783 verror (m, ap);
1786 DEFUN ("commandp", Fcommandp, Scommandp, 1, 2, 0,
1787 doc: /* Non-nil if FUNCTION makes provisions for interactive calling.
1788 This means it contains a description for how to read arguments to give it.
1789 The value is nil for an invalid function or a symbol with no function
1790 definition.
1792 Interactively callable functions include strings and vectors (treated
1793 as keyboard macros), lambda-expressions that contain a top-level call
1794 to `interactive', autoload definitions made by `autoload' with non-nil
1795 fourth argument, and some of the built-in functions of Lisp.
1797 Also, a symbol satisfies `commandp' if its function definition does so.
1799 If the optional argument FOR-CALL-INTERACTIVELY is non-nil,
1800 then strings and vectors are not accepted. */)
1801 (Lisp_Object function, Lisp_Object for_call_interactively)
1803 register Lisp_Object fun;
1804 register Lisp_Object funcar;
1805 Lisp_Object if_prop = Qnil;
1807 fun = function;
1809 fun = indirect_function (fun); /* Check cycles. */
1810 if (NILP (fun))
1811 return Qnil;
1813 /* Check an `interactive-form' property if present, analogous to the
1814 function-documentation property. */
1815 fun = function;
1816 while (SYMBOLP (fun))
1818 Lisp_Object tmp = Fget (fun, Qinteractive_form);
1819 if (!NILP (tmp))
1820 if_prop = Qt;
1821 fun = Fsymbol_function (fun);
1824 /* Emacs primitives are interactive if their DEFUN specifies an
1825 interactive spec. */
1826 if (SUBRP (fun))
1827 return XSUBR (fun)->intspec ? Qt : if_prop;
1829 /* Bytecode objects are interactive if they are long enough to
1830 have an element whose index is COMPILED_INTERACTIVE, which is
1831 where the interactive spec is stored. */
1832 else if (COMPILEDP (fun))
1833 return ((ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK) > COMPILED_INTERACTIVE
1834 ? Qt : if_prop);
1836 /* Strings and vectors are keyboard macros. */
1837 if (STRINGP (fun) || VECTORP (fun))
1838 return (NILP (for_call_interactively) ? Qt : Qnil);
1840 /* Lists may represent commands. */
1841 if (!CONSP (fun))
1842 return Qnil;
1843 funcar = XCAR (fun);
1844 if (EQ (funcar, Qclosure))
1845 return (!NILP (Fassq (Qinteractive, Fcdr (Fcdr (XCDR (fun)))))
1846 ? Qt : if_prop);
1847 else if (EQ (funcar, Qlambda))
1848 return !NILP (Fassq (Qinteractive, Fcdr (XCDR (fun)))) ? Qt : if_prop;
1849 else if (EQ (funcar, Qautoload))
1850 return !NILP (Fcar (Fcdr (Fcdr (XCDR (fun))))) ? Qt : if_prop;
1851 else
1852 return Qnil;
1855 DEFUN ("autoload", Fautoload, Sautoload, 2, 5, 0,
1856 doc: /* Define FUNCTION to autoload from FILE.
1857 FUNCTION is a symbol; FILE is a file name string to pass to `load'.
1858 Third arg DOCSTRING is documentation for the function.
1859 Fourth arg INTERACTIVE if non-nil says function can be called interactively.
1860 Fifth arg TYPE indicates the type of the object:
1861 nil or omitted says FUNCTION is a function,
1862 `keymap' says FUNCTION is really a keymap, and
1863 `macro' or t says FUNCTION is really a macro.
1864 Third through fifth args give info about the real definition.
1865 They default to nil.
1866 If FUNCTION is already defined other than as an autoload,
1867 this does nothing and returns nil. */)
1868 (Lisp_Object function, Lisp_Object file, Lisp_Object docstring, Lisp_Object interactive, Lisp_Object type)
1870 CHECK_SYMBOL (function);
1871 CHECK_STRING (file);
1873 /* If function is defined and not as an autoload, don't override. */
1874 if (!NILP (XSYMBOL (function)->function)
1875 && !AUTOLOADP (XSYMBOL (function)->function))
1876 return Qnil;
1878 if (!NILP (Vpurify_flag) && EQ (docstring, make_number (0)))
1879 /* `read1' in lread.c has found the docstring starting with "\
1880 and assumed the docstring will be provided by Snarf-documentation, so it
1881 passed us 0 instead. But that leads to accidental sharing in purecopy's
1882 hash-consing, so we use a (hopefully) unique integer instead. */
1883 docstring = make_number (XHASH (function));
1884 return Fdefalias (function,
1885 list5 (Qautoload, file, docstring, interactive, type),
1886 Qnil);
1889 void
1890 un_autoload (Lisp_Object oldqueue)
1892 Lisp_Object queue, first, second;
1894 /* Queue to unwind is current value of Vautoload_queue.
1895 oldqueue is the shadowed value to leave in Vautoload_queue. */
1896 queue = Vautoload_queue;
1897 Vautoload_queue = oldqueue;
1898 while (CONSP (queue))
1900 first = XCAR (queue);
1901 second = Fcdr (first);
1902 first = Fcar (first);
1903 if (EQ (first, make_number (0)))
1904 Vfeatures = second;
1905 else
1906 Ffset (first, second);
1907 queue = XCDR (queue);
1911 /* Load an autoloaded function.
1912 FUNNAME is the symbol which is the function's name.
1913 FUNDEF is the autoload definition (a list). */
1915 DEFUN ("autoload-do-load", Fautoload_do_load, Sautoload_do_load, 1, 3, 0,
1916 doc: /* Load FUNDEF which should be an autoload.
1917 If non-nil, FUNNAME should be the symbol whose function value is FUNDEF,
1918 in which case the function returns the new autoloaded function value.
1919 If equal to `macro', MACRO-ONLY specifies that FUNDEF should only be loaded if
1920 it is defines a macro. */)
1921 (Lisp_Object fundef, Lisp_Object funname, Lisp_Object macro_only)
1923 ptrdiff_t count = SPECPDL_INDEX ();
1924 struct gcpro gcpro1, gcpro2, gcpro3;
1926 if (!CONSP (fundef) || !EQ (Qautoload, XCAR (fundef)))
1927 return fundef;
1929 if (EQ (macro_only, Qmacro))
1931 Lisp_Object kind = Fnth (make_number (4), fundef);
1932 if (! (EQ (kind, Qt) || EQ (kind, Qmacro)))
1933 return fundef;
1936 /* This is to make sure that loadup.el gives a clear picture
1937 of what files are preloaded and when. */
1938 if (! NILP (Vpurify_flag))
1939 error ("Attempt to autoload %s while preparing to dump",
1940 SDATA (SYMBOL_NAME (funname)));
1942 CHECK_SYMBOL (funname);
1943 GCPRO3 (funname, fundef, macro_only);
1945 /* Preserve the match data. */
1946 record_unwind_save_match_data ();
1948 /* If autoloading gets an error (which includes the error of failing
1949 to define the function being called), we use Vautoload_queue
1950 to undo function definitions and `provide' calls made by
1951 the function. We do this in the specific case of autoloading
1952 because autoloading is not an explicit request "load this file",
1953 but rather a request to "call this function".
1955 The value saved here is to be restored into Vautoload_queue. */
1956 record_unwind_protect (un_autoload, Vautoload_queue);
1957 Vautoload_queue = Qt;
1958 /* If `macro_only', assume this autoload to be a "best-effort",
1959 so don't signal an error if autoloading fails. */
1960 Fload (Fcar (Fcdr (fundef)), macro_only, Qt, Qnil, Qt);
1962 /* Once loading finishes, don't undo it. */
1963 Vautoload_queue = Qt;
1964 unbind_to (count, Qnil);
1966 UNGCPRO;
1968 if (NILP (funname))
1969 return Qnil;
1970 else
1972 Lisp_Object fun = Findirect_function (funname, Qnil);
1974 if (!NILP (Fequal (fun, fundef)))
1975 error ("Autoloading failed to define function %s",
1976 SDATA (SYMBOL_NAME (funname)));
1977 else
1978 return fun;
1983 DEFUN ("eval", Feval, Seval, 1, 2, 0,
1984 doc: /* Evaluate FORM and return its value.
1985 If LEXICAL is t, evaluate using lexical scoping.
1986 LEXICAL can also be an actual lexical environment, in the form of an
1987 alist mapping symbols to their value. */)
1988 (Lisp_Object form, Lisp_Object lexical)
1990 ptrdiff_t count = SPECPDL_INDEX ();
1991 specbind (Qinternal_interpreter_environment,
1992 CONSP (lexical) || NILP (lexical) ? lexical : list1 (Qt));
1993 return unbind_to (count, eval_sub (form));
1996 /* Grow the specpdl stack by one entry.
1997 The caller should have already initialized the entry.
1998 Signal an error on stack overflow.
2000 Make sure that there is always one unused entry past the top of the
2001 stack, so that the just-initialized entry is safely unwound if
2002 memory exhausted and an error is signaled here. Also, allocate a
2003 never-used entry just before the bottom of the stack; sometimes its
2004 address is taken. */
2006 static void
2007 grow_specpdl (void)
2009 specpdl_ptr++;
2011 if (specpdl_ptr == specpdl + specpdl_size)
2013 ptrdiff_t count = SPECPDL_INDEX ();
2014 ptrdiff_t max_size = min (max_specpdl_size, PTRDIFF_MAX - 1000);
2015 union specbinding *pdlvec = specpdl - 1;
2016 ptrdiff_t pdlvecsize = specpdl_size + 1;
2017 if (max_size <= specpdl_size)
2019 if (max_specpdl_size < 400)
2020 max_size = max_specpdl_size = 400;
2021 if (max_size <= specpdl_size)
2022 signal_error ("Variable binding depth exceeds max-specpdl-size",
2023 Qnil);
2025 pdlvec = xpalloc (pdlvec, &pdlvecsize, 1, max_size + 1, sizeof *specpdl);
2026 specpdl = pdlvec + 1;
2027 specpdl_size = pdlvecsize - 1;
2028 specpdl_ptr = specpdl + count;
2032 ptrdiff_t
2033 record_in_backtrace (Lisp_Object function, Lisp_Object *args, ptrdiff_t nargs)
2035 ptrdiff_t count = SPECPDL_INDEX ();
2037 eassert (nargs >= UNEVALLED);
2038 specpdl_ptr->bt.kind = SPECPDL_BACKTRACE;
2039 specpdl_ptr->bt.debug_on_exit = false;
2040 specpdl_ptr->bt.function = function;
2041 specpdl_ptr->bt.args = args;
2042 specpdl_ptr->bt.nargs = nargs;
2043 grow_specpdl ();
2045 return count;
2048 /* Eval a sub-expression of the current expression (i.e. in the same
2049 lexical scope). */
2050 Lisp_Object
2051 eval_sub (Lisp_Object form)
2053 Lisp_Object fun, val, original_fun, original_args;
2054 Lisp_Object funcar;
2055 struct gcpro gcpro1, gcpro2, gcpro3;
2056 ptrdiff_t count;
2058 if (SYMBOLP (form))
2060 /* Look up its binding in the lexical environment.
2061 We do not pay attention to the declared_special flag here, since we
2062 already did that when let-binding the variable. */
2063 Lisp_Object lex_binding
2064 = !NILP (Vinternal_interpreter_environment) /* Mere optimization! */
2065 ? Fassq (form, Vinternal_interpreter_environment)
2066 : Qnil;
2067 if (CONSP (lex_binding))
2068 return XCDR (lex_binding);
2069 else
2070 return Fsymbol_value (form);
2073 if (!CONSP (form))
2074 return form;
2076 QUIT;
2078 GCPRO1 (form);
2079 maybe_gc ();
2080 UNGCPRO;
2082 if (++lisp_eval_depth > max_lisp_eval_depth)
2084 if (max_lisp_eval_depth < 100)
2085 max_lisp_eval_depth = 100;
2086 if (lisp_eval_depth > max_lisp_eval_depth)
2087 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2090 original_fun = XCAR (form);
2091 original_args = XCDR (form);
2093 /* This also protects them from gc. */
2094 count = record_in_backtrace (original_fun, &original_args, UNEVALLED);
2096 if (debug_on_next_call)
2097 do_debug_on_call (Qt, count);
2099 /* At this point, only original_fun and original_args
2100 have values that will be used below. */
2101 retry:
2103 /* Optimize for no indirection. */
2104 fun = original_fun;
2105 if (!SYMBOLP (fun))
2106 fun = Ffunction (Fcons (fun, Qnil));
2107 else if (!NILP (fun) && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2108 fun = indirect_function (fun);
2110 if (SUBRP (fun))
2112 Lisp_Object numargs;
2113 Lisp_Object argvals[8];
2114 Lisp_Object args_left;
2115 register int i, maxargs;
2117 args_left = original_args;
2118 numargs = Flength (args_left);
2120 check_cons_list ();
2122 if (XINT (numargs) < XSUBR (fun)->min_args
2123 || (XSUBR (fun)->max_args >= 0
2124 && XSUBR (fun)->max_args < XINT (numargs)))
2125 xsignal2 (Qwrong_number_of_arguments, original_fun, numargs);
2127 else if (XSUBR (fun)->max_args == UNEVALLED)
2128 val = (XSUBR (fun)->function.aUNEVALLED) (args_left);
2129 else if (XSUBR (fun)->max_args == MANY)
2131 /* Pass a vector of evaluated arguments. */
2132 Lisp_Object *vals;
2133 ptrdiff_t argnum = 0;
2134 USE_SAFE_ALLOCA;
2136 SAFE_ALLOCA_LISP (vals, XINT (numargs));
2138 GCPRO3 (args_left, fun, fun);
2139 gcpro3.var = vals;
2140 gcpro3.nvars = 0;
2142 while (!NILP (args_left))
2144 vals[argnum++] = eval_sub (Fcar (args_left));
2145 args_left = Fcdr (args_left);
2146 gcpro3.nvars = argnum;
2149 set_backtrace_args (specpdl + count, vals, XINT (numargs));
2151 val = (XSUBR (fun)->function.aMANY) (XINT (numargs), vals);
2152 UNGCPRO;
2153 SAFE_FREE ();
2155 else
2157 GCPRO3 (args_left, fun, fun);
2158 gcpro3.var = argvals;
2159 gcpro3.nvars = 0;
2161 maxargs = XSUBR (fun)->max_args;
2162 for (i = 0; i < maxargs; args_left = Fcdr (args_left))
2164 argvals[i] = eval_sub (Fcar (args_left));
2165 gcpro3.nvars = ++i;
2168 UNGCPRO;
2170 set_backtrace_args (specpdl + count, argvals, XINT (numargs));
2172 switch (i)
2174 case 0:
2175 val = (XSUBR (fun)->function.a0 ());
2176 break;
2177 case 1:
2178 val = (XSUBR (fun)->function.a1 (argvals[0]));
2179 break;
2180 case 2:
2181 val = (XSUBR (fun)->function.a2 (argvals[0], argvals[1]));
2182 break;
2183 case 3:
2184 val = (XSUBR (fun)->function.a3
2185 (argvals[0], argvals[1], argvals[2]));
2186 break;
2187 case 4:
2188 val = (XSUBR (fun)->function.a4
2189 (argvals[0], argvals[1], argvals[2], argvals[3]));
2190 break;
2191 case 5:
2192 val = (XSUBR (fun)->function.a5
2193 (argvals[0], argvals[1], argvals[2], argvals[3],
2194 argvals[4]));
2195 break;
2196 case 6:
2197 val = (XSUBR (fun)->function.a6
2198 (argvals[0], argvals[1], argvals[2], argvals[3],
2199 argvals[4], argvals[5]));
2200 break;
2201 case 7:
2202 val = (XSUBR (fun)->function.a7
2203 (argvals[0], argvals[1], argvals[2], argvals[3],
2204 argvals[4], argvals[5], argvals[6]));
2205 break;
2207 case 8:
2208 val = (XSUBR (fun)->function.a8
2209 (argvals[0], argvals[1], argvals[2], argvals[3],
2210 argvals[4], argvals[5], argvals[6], argvals[7]));
2211 break;
2213 default:
2214 /* Someone has created a subr that takes more arguments than
2215 is supported by this code. We need to either rewrite the
2216 subr to use a different argument protocol, or add more
2217 cases to this switch. */
2218 emacs_abort ();
2222 else if (COMPILEDP (fun))
2223 val = apply_lambda (fun, original_args, count);
2224 else
2226 if (NILP (fun))
2227 xsignal1 (Qvoid_function, original_fun);
2228 if (!CONSP (fun))
2229 xsignal1 (Qinvalid_function, original_fun);
2230 funcar = XCAR (fun);
2231 if (!SYMBOLP (funcar))
2232 xsignal1 (Qinvalid_function, original_fun);
2233 if (EQ (funcar, Qautoload))
2235 Fautoload_do_load (fun, original_fun, Qnil);
2236 goto retry;
2238 if (EQ (funcar, Qmacro))
2240 ptrdiff_t count1 = SPECPDL_INDEX ();
2241 Lisp_Object exp;
2242 /* Bind lexical-binding during expansion of the macro, so the
2243 macro can know reliably if the code it outputs will be
2244 interpreted using lexical-binding or not. */
2245 specbind (Qlexical_binding,
2246 NILP (Vinternal_interpreter_environment) ? Qnil : Qt);
2247 exp = apply1 (Fcdr (fun), original_args);
2248 unbind_to (count1, Qnil);
2249 val = eval_sub (exp);
2251 else if (EQ (funcar, Qlambda)
2252 || EQ (funcar, Qclosure))
2253 val = apply_lambda (fun, original_args, count);
2254 else
2255 xsignal1 (Qinvalid_function, original_fun);
2257 check_cons_list ();
2259 lisp_eval_depth--;
2260 if (backtrace_debug_on_exit (specpdl + count))
2261 val = call_debugger (list2 (Qexit, val));
2262 specpdl_ptr--;
2264 return val;
2267 DEFUN ("apply", Fapply, Sapply, 1, MANY, 0,
2268 doc: /* Call FUNCTION with our remaining args, using our last arg as list of args.
2269 Then return the value FUNCTION returns.
2270 Thus, (apply '+ 1 2 '(3 4)) returns 10.
2271 usage: (apply FUNCTION &rest ARGUMENTS) */)
2272 (ptrdiff_t nargs, Lisp_Object *args)
2274 ptrdiff_t i, numargs, funcall_nargs;
2275 register Lisp_Object spread_arg;
2276 register Lisp_Object *funcall_args;
2277 Lisp_Object fun, retval;
2278 USE_SAFE_ALLOCA;
2280 fun = args [0];
2281 funcall_args = 0;
2282 spread_arg = args [nargs - 1];
2283 CHECK_LIST (spread_arg);
2285 numargs = XINT (Flength (spread_arg));
2287 if (numargs == 0)
2288 return Ffuncall (nargs - 1, args);
2289 else if (numargs == 1)
2291 args [nargs - 1] = XCAR (spread_arg);
2292 return Ffuncall (nargs, args);
2295 numargs += nargs - 2;
2297 /* Optimize for no indirection. */
2298 if (SYMBOLP (fun) && !NILP (fun)
2299 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2300 fun = indirect_function (fun);
2301 if (NILP (fun))
2303 /* Let funcall get the error. */
2304 fun = args[0];
2305 goto funcall;
2308 if (SUBRP (fun))
2310 if (numargs < XSUBR (fun)->min_args
2311 || (XSUBR (fun)->max_args >= 0 && XSUBR (fun)->max_args < numargs))
2312 goto funcall; /* Let funcall get the error. */
2313 else if (XSUBR (fun)->max_args >= 0 && XSUBR (fun)->max_args > numargs)
2315 /* Avoid making funcall cons up a yet another new vector of arguments
2316 by explicitly supplying nil's for optional values. */
2317 SAFE_ALLOCA_LISP (funcall_args, 1 + XSUBR (fun)->max_args);
2318 for (i = numargs; i < XSUBR (fun)->max_args; /* nothing */)
2319 funcall_args[++i] = Qnil;
2320 funcall_nargs = 1 + XSUBR (fun)->max_args;
2323 funcall:
2324 /* We add 1 to numargs because funcall_args includes the
2325 function itself as well as its arguments. */
2326 if (!funcall_args)
2328 SAFE_ALLOCA_LISP (funcall_args, 1 + numargs);
2329 funcall_nargs = 1 + numargs;
2332 memcpy (funcall_args, args, nargs * word_size);
2333 /* Spread the last arg we got. Its first element goes in
2334 the slot that it used to occupy, hence this value of I. */
2335 i = nargs - 1;
2336 while (!NILP (spread_arg))
2338 funcall_args [i++] = XCAR (spread_arg);
2339 spread_arg = XCDR (spread_arg);
2342 /* Ffuncall gcpro's all of its args. */
2343 retval = Ffuncall (funcall_nargs, funcall_args);
2345 SAFE_FREE ();
2346 return retval;
2349 /* Run hook variables in various ways. */
2351 static Lisp_Object
2352 funcall_nil (ptrdiff_t nargs, Lisp_Object *args)
2354 Ffuncall (nargs, args);
2355 return Qnil;
2358 DEFUN ("run-hooks", Frun_hooks, Srun_hooks, 0, MANY, 0,
2359 doc: /* Run each hook in HOOKS.
2360 Each argument should be a symbol, a hook variable.
2361 These symbols are processed in the order specified.
2362 If a hook symbol has a non-nil value, that value may be a function
2363 or a list of functions to be called to run the hook.
2364 If the value is a function, it is called with no arguments.
2365 If it is a list, the elements are called, in order, with no arguments.
2367 Major modes should not use this function directly to run their mode
2368 hook; they should use `run-mode-hooks' instead.
2370 Do not use `make-local-variable' to make a hook variable buffer-local.
2371 Instead, use `add-hook' and specify t for the LOCAL argument.
2372 usage: (run-hooks &rest HOOKS) */)
2373 (ptrdiff_t nargs, Lisp_Object *args)
2375 Lisp_Object hook[1];
2376 ptrdiff_t i;
2378 for (i = 0; i < nargs; i++)
2380 hook[0] = args[i];
2381 run_hook_with_args (1, hook, funcall_nil);
2384 return Qnil;
2387 DEFUN ("run-hook-with-args", Frun_hook_with_args,
2388 Srun_hook_with_args, 1, MANY, 0,
2389 doc: /* Run HOOK with the specified arguments ARGS.
2390 HOOK should be a symbol, a hook variable. The value of HOOK
2391 may be nil, a function, or a list of functions. Call each
2392 function in order with arguments ARGS. The final return value
2393 is unspecified.
2395 Do not use `make-local-variable' to make a hook variable buffer-local.
2396 Instead, use `add-hook' and specify t for the LOCAL argument.
2397 usage: (run-hook-with-args HOOK &rest ARGS) */)
2398 (ptrdiff_t nargs, Lisp_Object *args)
2400 return run_hook_with_args (nargs, args, funcall_nil);
2403 /* NB this one still documents a specific non-nil return value.
2404 (As did run-hook-with-args and run-hook-with-args-until-failure
2405 until they were changed in 24.1.) */
2406 DEFUN ("run-hook-with-args-until-success", Frun_hook_with_args_until_success,
2407 Srun_hook_with_args_until_success, 1, MANY, 0,
2408 doc: /* Run HOOK with the specified arguments ARGS.
2409 HOOK should be a symbol, a hook variable. The value of HOOK
2410 may be nil, a function, or a list of functions. Call each
2411 function in order with arguments ARGS, stopping at the first
2412 one that returns non-nil, and return that value. Otherwise (if
2413 all functions return nil, or if there are no functions to call),
2414 return nil.
2416 Do not use `make-local-variable' to make a hook variable buffer-local.
2417 Instead, use `add-hook' and specify t for the LOCAL argument.
2418 usage: (run-hook-with-args-until-success HOOK &rest ARGS) */)
2419 (ptrdiff_t nargs, Lisp_Object *args)
2421 return run_hook_with_args (nargs, args, Ffuncall);
2424 static Lisp_Object
2425 funcall_not (ptrdiff_t nargs, Lisp_Object *args)
2427 return NILP (Ffuncall (nargs, args)) ? Qt : Qnil;
2430 DEFUN ("run-hook-with-args-until-failure", Frun_hook_with_args_until_failure,
2431 Srun_hook_with_args_until_failure, 1, MANY, 0,
2432 doc: /* Run HOOK with the specified arguments ARGS.
2433 HOOK should be a symbol, a hook variable. The value of HOOK
2434 may be nil, a function, or a list of functions. Call each
2435 function in order with arguments ARGS, stopping at the first
2436 one that returns nil, and return nil. Otherwise (if all functions
2437 return non-nil, or if there are no functions to call), return non-nil
2438 \(do not rely on the precise return value in this case).
2440 Do not use `make-local-variable' to make a hook variable buffer-local.
2441 Instead, use `add-hook' and specify t for the LOCAL argument.
2442 usage: (run-hook-with-args-until-failure HOOK &rest ARGS) */)
2443 (ptrdiff_t nargs, Lisp_Object *args)
2445 return NILP (run_hook_with_args (nargs, args, funcall_not)) ? Qt : Qnil;
2448 static Lisp_Object
2449 run_hook_wrapped_funcall (ptrdiff_t nargs, Lisp_Object *args)
2451 Lisp_Object tmp = args[0], ret;
2452 args[0] = args[1];
2453 args[1] = tmp;
2454 ret = Ffuncall (nargs, args);
2455 args[1] = args[0];
2456 args[0] = tmp;
2457 return ret;
2460 DEFUN ("run-hook-wrapped", Frun_hook_wrapped, Srun_hook_wrapped, 2, MANY, 0,
2461 doc: /* Run HOOK, passing each function through WRAP-FUNCTION.
2462 I.e. instead of calling each function FUN directly with arguments ARGS,
2463 it calls WRAP-FUNCTION with arguments FUN and ARGS.
2464 As soon as a call to WRAP-FUNCTION returns non-nil, `run-hook-wrapped'
2465 aborts and returns that value.
2466 usage: (run-hook-wrapped HOOK WRAP-FUNCTION &rest ARGS) */)
2467 (ptrdiff_t nargs, Lisp_Object *args)
2469 return run_hook_with_args (nargs, args, run_hook_wrapped_funcall);
2472 /* ARGS[0] should be a hook symbol.
2473 Call each of the functions in the hook value, passing each of them
2474 as arguments all the rest of ARGS (all NARGS - 1 elements).
2475 FUNCALL specifies how to call each function on the hook.
2476 The caller (or its caller, etc) must gcpro all of ARGS,
2477 except that it isn't necessary to gcpro ARGS[0]. */
2479 Lisp_Object
2480 run_hook_with_args (ptrdiff_t nargs, Lisp_Object *args,
2481 Lisp_Object (*funcall) (ptrdiff_t nargs, Lisp_Object *args))
2483 Lisp_Object sym, val, ret = Qnil;
2484 struct gcpro gcpro1, gcpro2, gcpro3;
2486 /* If we are dying or still initializing,
2487 don't do anything--it would probably crash if we tried. */
2488 if (NILP (Vrun_hooks))
2489 return Qnil;
2491 sym = args[0];
2492 val = find_symbol_value (sym);
2494 if (EQ (val, Qunbound) || NILP (val))
2495 return ret;
2496 else if (!CONSP (val) || FUNCTIONP (val))
2498 args[0] = val;
2499 return funcall (nargs, args);
2501 else
2503 Lisp_Object global_vals = Qnil;
2504 GCPRO3 (sym, val, global_vals);
2506 for (;
2507 CONSP (val) && NILP (ret);
2508 val = XCDR (val))
2510 if (EQ (XCAR (val), Qt))
2512 /* t indicates this hook has a local binding;
2513 it means to run the global binding too. */
2514 global_vals = Fdefault_value (sym);
2515 if (NILP (global_vals)) continue;
2517 if (!CONSP (global_vals) || EQ (XCAR (global_vals), Qlambda))
2519 args[0] = global_vals;
2520 ret = funcall (nargs, args);
2522 else
2524 for (;
2525 CONSP (global_vals) && NILP (ret);
2526 global_vals = XCDR (global_vals))
2528 args[0] = XCAR (global_vals);
2529 /* In a global value, t should not occur. If it does, we
2530 must ignore it to avoid an endless loop. */
2531 if (!EQ (args[0], Qt))
2532 ret = funcall (nargs, args);
2536 else
2538 args[0] = XCAR (val);
2539 ret = funcall (nargs, args);
2543 UNGCPRO;
2544 return ret;
2548 /* Run the hook HOOK, giving each function the two args ARG1 and ARG2. */
2550 void
2551 run_hook_with_args_2 (Lisp_Object hook, Lisp_Object arg1, Lisp_Object arg2)
2553 Frun_hook_with_args (3, ((Lisp_Object []) { hook, arg1, arg2 }));
2556 /* Apply fn to arg. */
2557 Lisp_Object
2558 apply1 (Lisp_Object fn, Lisp_Object arg)
2560 return (NILP (arg) ? Ffuncall (1, &fn)
2561 : Fapply (2, ((Lisp_Object []) { fn, arg })));
2564 /* Call function fn on no arguments. */
2565 Lisp_Object
2566 call0 (Lisp_Object fn)
2568 return Ffuncall (1, &fn);
2571 /* Call function fn with 1 argument arg1. */
2572 /* ARGSUSED */
2573 Lisp_Object
2574 call1 (Lisp_Object fn, Lisp_Object arg1)
2576 return Ffuncall (2, ((Lisp_Object []) { fn, arg1 }));
2579 /* Call function fn with 2 arguments arg1, arg2. */
2580 /* ARGSUSED */
2581 Lisp_Object
2582 call2 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2)
2584 return Ffuncall (3, ((Lisp_Object []) { fn, arg1, arg2 }));
2587 /* Call function fn with 3 arguments arg1, arg2, arg3. */
2588 /* ARGSUSED */
2589 Lisp_Object
2590 call3 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2592 return Ffuncall (4, ((Lisp_Object []) { fn, arg1, arg2, arg3 }));
2595 /* Call function fn with 4 arguments arg1, arg2, arg3, arg4. */
2596 /* ARGSUSED */
2597 Lisp_Object
2598 call4 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2599 Lisp_Object arg4)
2601 return Ffuncall (5, ((Lisp_Object []) { fn, arg1, arg2, arg3, arg4 }));
2604 /* Call function fn with 5 arguments arg1, arg2, arg3, arg4, arg5. */
2605 /* ARGSUSED */
2606 Lisp_Object
2607 call5 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2608 Lisp_Object arg4, Lisp_Object arg5)
2610 return Ffuncall (6, ((Lisp_Object []) { fn, arg1, arg2, arg3, arg4, arg5 }));
2613 /* Call function fn with 6 arguments arg1, arg2, arg3, arg4, arg5, arg6. */
2614 /* ARGSUSED */
2615 Lisp_Object
2616 call6 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2617 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6)
2619 return Ffuncall (7, ((Lisp_Object [])
2620 { 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 Ffuncall (8, ((Lisp_Object [])
2630 { fn, arg1, arg2, arg3, arg4, arg5, arg6, arg7 }));
2633 /* The caller should GCPRO all the elements of ARGS. */
2635 DEFUN ("functionp", Ffunctionp, Sfunctionp, 1, 1, 0,
2636 doc: /* Non-nil if OBJECT is a function. */)
2637 (Lisp_Object object)
2639 if (FUNCTIONP (object))
2640 return Qt;
2641 return Qnil;
2644 DEFUN ("funcall", Ffuncall, Sfuncall, 1, MANY, 0,
2645 doc: /* Call first argument as a function, passing remaining arguments to it.
2646 Return the value that function returns.
2647 Thus, (funcall 'cons 'x 'y) returns (x . y).
2648 usage: (funcall FUNCTION &rest ARGUMENTS) */)
2649 (ptrdiff_t nargs, Lisp_Object *args)
2651 Lisp_Object fun, original_fun;
2652 Lisp_Object funcar;
2653 ptrdiff_t numargs = nargs - 1;
2654 Lisp_Object lisp_numargs;
2655 Lisp_Object val;
2656 register Lisp_Object *internal_args;
2657 ptrdiff_t i, count;
2659 QUIT;
2661 if (++lisp_eval_depth > max_lisp_eval_depth)
2663 if (max_lisp_eval_depth < 100)
2664 max_lisp_eval_depth = 100;
2665 if (lisp_eval_depth > max_lisp_eval_depth)
2666 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2669 /* This also GCPROs them. */
2670 count = record_in_backtrace (args[0], &args[1], nargs - 1);
2672 /* Call GC after setting up the backtrace, so the latter GCPROs the args. */
2673 maybe_gc ();
2675 if (debug_on_next_call)
2676 do_debug_on_call (Qlambda, count);
2678 check_cons_list ();
2680 original_fun = args[0];
2682 retry:
2684 /* Optimize for no indirection. */
2685 fun = original_fun;
2686 if (SYMBOLP (fun) && !NILP (fun)
2687 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2688 fun = indirect_function (fun);
2690 if (SUBRP (fun))
2692 if (numargs < XSUBR (fun)->min_args
2693 || (XSUBR (fun)->max_args >= 0 && XSUBR (fun)->max_args < numargs))
2695 XSETFASTINT (lisp_numargs, numargs);
2696 xsignal2 (Qwrong_number_of_arguments, original_fun, lisp_numargs);
2699 else if (XSUBR (fun)->max_args == UNEVALLED)
2700 xsignal1 (Qinvalid_function, original_fun);
2702 else if (XSUBR (fun)->max_args == MANY)
2703 val = (XSUBR (fun)->function.aMANY) (numargs, args + 1);
2704 else
2706 Lisp_Object internal_argbuf[8];
2707 if (XSUBR (fun)->max_args > numargs)
2709 eassert (XSUBR (fun)->max_args <= ARRAYELTS (internal_argbuf));
2710 internal_args = internal_argbuf;
2711 memcpy (internal_args, args + 1, numargs * word_size);
2712 for (i = numargs; i < XSUBR (fun)->max_args; i++)
2713 internal_args[i] = Qnil;
2715 else
2716 internal_args = args + 1;
2717 switch (XSUBR (fun)->max_args)
2719 case 0:
2720 val = (XSUBR (fun)->function.a0 ());
2721 break;
2722 case 1:
2723 val = (XSUBR (fun)->function.a1 (internal_args[0]));
2724 break;
2725 case 2:
2726 val = (XSUBR (fun)->function.a2
2727 (internal_args[0], internal_args[1]));
2728 break;
2729 case 3:
2730 val = (XSUBR (fun)->function.a3
2731 (internal_args[0], internal_args[1], internal_args[2]));
2732 break;
2733 case 4:
2734 val = (XSUBR (fun)->function.a4
2735 (internal_args[0], internal_args[1], internal_args[2],
2736 internal_args[3]));
2737 break;
2738 case 5:
2739 val = (XSUBR (fun)->function.a5
2740 (internal_args[0], internal_args[1], internal_args[2],
2741 internal_args[3], internal_args[4]));
2742 break;
2743 case 6:
2744 val = (XSUBR (fun)->function.a6
2745 (internal_args[0], internal_args[1], internal_args[2],
2746 internal_args[3], internal_args[4], internal_args[5]));
2747 break;
2748 case 7:
2749 val = (XSUBR (fun)->function.a7
2750 (internal_args[0], internal_args[1], internal_args[2],
2751 internal_args[3], internal_args[4], internal_args[5],
2752 internal_args[6]));
2753 break;
2755 case 8:
2756 val = (XSUBR (fun)->function.a8
2757 (internal_args[0], internal_args[1], internal_args[2],
2758 internal_args[3], internal_args[4], internal_args[5],
2759 internal_args[6], internal_args[7]));
2760 break;
2762 default:
2764 /* If a subr takes more than 8 arguments without using MANY
2765 or UNEVALLED, we need to extend this function to support it.
2766 Until this is done, there is no way to call the function. */
2767 emacs_abort ();
2771 else if (COMPILEDP (fun))
2772 val = funcall_lambda (fun, numargs, args + 1);
2773 else
2775 if (NILP (fun))
2776 xsignal1 (Qvoid_function, original_fun);
2777 if (!CONSP (fun))
2778 xsignal1 (Qinvalid_function, original_fun);
2779 funcar = XCAR (fun);
2780 if (!SYMBOLP (funcar))
2781 xsignal1 (Qinvalid_function, original_fun);
2782 if (EQ (funcar, Qlambda)
2783 || EQ (funcar, Qclosure))
2784 val = funcall_lambda (fun, numargs, args + 1);
2785 else if (EQ (funcar, Qautoload))
2787 Fautoload_do_load (fun, original_fun, Qnil);
2788 check_cons_list ();
2789 goto retry;
2791 else
2792 xsignal1 (Qinvalid_function, original_fun);
2794 check_cons_list ();
2795 lisp_eval_depth--;
2796 if (backtrace_debug_on_exit (specpdl + count))
2797 val = call_debugger (list2 (Qexit, val));
2798 specpdl_ptr--;
2799 return val;
2802 static Lisp_Object
2803 apply_lambda (Lisp_Object fun, Lisp_Object args, ptrdiff_t count)
2805 Lisp_Object args_left;
2806 ptrdiff_t i;
2807 EMACS_INT numargs;
2808 register Lisp_Object *arg_vector;
2809 struct gcpro gcpro1, gcpro2, gcpro3;
2810 register Lisp_Object tem;
2811 USE_SAFE_ALLOCA;
2813 numargs = XFASTINT (Flength (args));
2814 SAFE_ALLOCA_LISP (arg_vector, numargs);
2815 args_left = args;
2817 GCPRO3 (*arg_vector, args_left, fun);
2818 gcpro1.nvars = 0;
2820 for (i = 0; i < numargs; )
2822 tem = Fcar (args_left), args_left = Fcdr (args_left);
2823 tem = eval_sub (tem);
2824 arg_vector[i++] = tem;
2825 gcpro1.nvars = i;
2828 UNGCPRO;
2830 set_backtrace_args (specpdl + count, arg_vector, i);
2831 tem = funcall_lambda (fun, numargs, arg_vector);
2833 /* Do the debug-on-exit now, while arg_vector still exists. */
2834 if (backtrace_debug_on_exit (specpdl + count))
2836 /* Don't do it again when we return to eval. */
2837 set_backtrace_debug_on_exit (specpdl + count, false);
2838 tem = call_debugger (list2 (Qexit, tem));
2840 SAFE_FREE ();
2841 return tem;
2844 /* Apply a Lisp function FUN to the NARGS evaluated arguments in ARG_VECTOR
2845 and return the result of evaluation.
2846 FUN must be either a lambda-expression or a compiled-code object. */
2848 static Lisp_Object
2849 funcall_lambda (Lisp_Object fun, ptrdiff_t nargs,
2850 register Lisp_Object *arg_vector)
2852 Lisp_Object val, syms_left, next, lexenv;
2853 ptrdiff_t count = SPECPDL_INDEX ();
2854 ptrdiff_t i;
2855 bool optional, rest;
2857 if (CONSP (fun))
2859 if (EQ (XCAR (fun), Qclosure))
2861 fun = XCDR (fun); /* Drop `closure'. */
2862 lexenv = XCAR (fun);
2863 CHECK_LIST_CONS (fun, fun);
2865 else
2866 lexenv = Qnil;
2867 syms_left = XCDR (fun);
2868 if (CONSP (syms_left))
2869 syms_left = XCAR (syms_left);
2870 else
2871 xsignal1 (Qinvalid_function, fun);
2873 else if (COMPILEDP (fun))
2875 syms_left = AREF (fun, COMPILED_ARGLIST);
2876 if (INTEGERP (syms_left))
2877 /* A byte-code object with a non-nil `push args' slot means we
2878 shouldn't bind any arguments, instead just call the byte-code
2879 interpreter directly; it will push arguments as necessary.
2881 Byte-code objects with either a non-existent, or a nil value for
2882 the `push args' slot (the default), have dynamically-bound
2883 arguments, and use the argument-binding code below instead (as do
2884 all interpreted functions, even lexically bound ones). */
2886 /* If we have not actually read the bytecode string
2887 and constants vector yet, fetch them from the file. */
2888 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2889 Ffetch_bytecode (fun);
2890 return exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2891 AREF (fun, COMPILED_CONSTANTS),
2892 AREF (fun, COMPILED_STACK_DEPTH),
2893 syms_left,
2894 nargs, arg_vector);
2896 lexenv = Qnil;
2898 else
2899 emacs_abort ();
2901 i = optional = rest = 0;
2902 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
2904 QUIT;
2906 next = XCAR (syms_left);
2907 if (!SYMBOLP (next))
2908 xsignal1 (Qinvalid_function, fun);
2910 if (EQ (next, Qand_rest))
2911 rest = 1;
2912 else if (EQ (next, Qand_optional))
2913 optional = 1;
2914 else
2916 Lisp_Object arg;
2917 if (rest)
2919 arg = Flist (nargs - i, &arg_vector[i]);
2920 i = nargs;
2922 else if (i < nargs)
2923 arg = arg_vector[i++];
2924 else if (!optional)
2925 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2926 else
2927 arg = Qnil;
2929 /* Bind the argument. */
2930 if (!NILP (lexenv) && SYMBOLP (next))
2931 /* Lexically bind NEXT by adding it to the lexenv alist. */
2932 lexenv = Fcons (Fcons (next, arg), lexenv);
2933 else
2934 /* Dynamically bind NEXT. */
2935 specbind (next, arg);
2939 if (!NILP (syms_left))
2940 xsignal1 (Qinvalid_function, fun);
2941 else if (i < nargs)
2942 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2944 if (!EQ (lexenv, Vinternal_interpreter_environment))
2945 /* Instantiate a new lexical environment. */
2946 specbind (Qinternal_interpreter_environment, lexenv);
2948 if (CONSP (fun))
2949 val = Fprogn (XCDR (XCDR (fun)));
2950 else
2952 /* If we have not actually read the bytecode string
2953 and constants vector yet, fetch them from the file. */
2954 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2955 Ffetch_bytecode (fun);
2956 val = exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2957 AREF (fun, COMPILED_CONSTANTS),
2958 AREF (fun, COMPILED_STACK_DEPTH),
2959 Qnil, 0, 0);
2962 return unbind_to (count, val);
2965 DEFUN ("fetch-bytecode", Ffetch_bytecode, Sfetch_bytecode,
2966 1, 1, 0,
2967 doc: /* If byte-compiled OBJECT is lazy-loaded, fetch it now. */)
2968 (Lisp_Object object)
2970 Lisp_Object tem;
2972 if (COMPILEDP (object) && CONSP (AREF (object, COMPILED_BYTECODE)))
2974 tem = read_doc_string (AREF (object, COMPILED_BYTECODE));
2975 if (!CONSP (tem))
2977 tem = AREF (object, COMPILED_BYTECODE);
2978 if (CONSP (tem) && STRINGP (XCAR (tem)))
2979 error ("Invalid byte code in %s", SDATA (XCAR (tem)));
2980 else
2981 error ("Invalid byte code");
2983 ASET (object, COMPILED_BYTECODE, XCAR (tem));
2984 ASET (object, COMPILED_CONSTANTS, XCDR (tem));
2986 return object;
2989 /* Return true if SYMBOL currently has a let-binding
2990 which was made in the buffer that is now current. */
2992 bool
2993 let_shadows_buffer_binding_p (struct Lisp_Symbol *symbol)
2995 union specbinding *p;
2996 Lisp_Object buf = Fcurrent_buffer ();
2998 for (p = specpdl_ptr; p > specpdl; )
2999 if ((--p)->kind > SPECPDL_LET)
3001 struct Lisp_Symbol *let_bound_symbol = XSYMBOL (specpdl_symbol (p));
3002 eassert (let_bound_symbol->redirect != SYMBOL_VARALIAS);
3003 if (symbol == let_bound_symbol
3004 && EQ (specpdl_where (p), buf))
3005 return 1;
3008 return 0;
3011 bool
3012 let_shadows_global_binding_p (Lisp_Object symbol)
3014 union specbinding *p;
3016 for (p = specpdl_ptr; p > specpdl; )
3017 if ((--p)->kind >= SPECPDL_LET && EQ (specpdl_symbol (p), symbol))
3018 return 1;
3020 return 0;
3023 /* `specpdl_ptr' describes which variable is
3024 let-bound, so it can be properly undone when we unbind_to.
3025 It can be either a plain SPECPDL_LET or a SPECPDL_LET_LOCAL/DEFAULT.
3026 - SYMBOL is the variable being bound. Note that it should not be
3027 aliased (i.e. when let-binding V1 that's aliased to V2, we want
3028 to record V2 here).
3029 - WHERE tells us in which buffer the binding took place.
3030 This is used for SPECPDL_LET_LOCAL bindings (i.e. bindings to a
3031 buffer-local variable) as well as for SPECPDL_LET_DEFAULT bindings,
3032 i.e. bindings to the default value of a variable which can be
3033 buffer-local. */
3035 void
3036 specbind (Lisp_Object symbol, Lisp_Object value)
3038 struct Lisp_Symbol *sym;
3040 CHECK_SYMBOL (symbol);
3041 sym = XSYMBOL (symbol);
3043 start:
3044 switch (sym->redirect)
3046 case SYMBOL_VARALIAS:
3047 sym = indirect_variable (sym); XSETSYMBOL (symbol, sym); goto start;
3048 case SYMBOL_PLAINVAL:
3049 /* The most common case is that of a non-constant symbol with a
3050 trivial value. Make that as fast as we can. */
3051 specpdl_ptr->let.kind = SPECPDL_LET;
3052 specpdl_ptr->let.symbol = symbol;
3053 specpdl_ptr->let.old_value = SYMBOL_VAL (sym);
3054 grow_specpdl ();
3055 if (!sym->constant)
3056 SET_SYMBOL_VAL (sym, value);
3057 else
3058 set_internal (symbol, value, Qnil, 1);
3059 break;
3060 case SYMBOL_LOCALIZED:
3061 if (SYMBOL_BLV (sym)->frame_local)
3062 error ("Frame-local vars cannot be let-bound");
3063 case SYMBOL_FORWARDED:
3065 Lisp_Object ovalue = find_symbol_value (symbol);
3066 specpdl_ptr->let.kind = SPECPDL_LET_LOCAL;
3067 specpdl_ptr->let.symbol = symbol;
3068 specpdl_ptr->let.old_value = ovalue;
3069 specpdl_ptr->let.where = Fcurrent_buffer ();
3071 eassert (sym->redirect != SYMBOL_LOCALIZED
3072 || (EQ (SYMBOL_BLV (sym)->where, Fcurrent_buffer ())));
3074 if (sym->redirect == SYMBOL_LOCALIZED)
3076 if (!blv_found (SYMBOL_BLV (sym)))
3077 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3079 else if (BUFFER_OBJFWDP (SYMBOL_FWD (sym)))
3081 /* If SYMBOL is a per-buffer variable which doesn't have a
3082 buffer-local value here, make the `let' change the global
3083 value by changing the value of SYMBOL in all buffers not
3084 having their own value. This is consistent with what
3085 happens with other buffer-local variables. */
3086 if (NILP (Flocal_variable_p (symbol, Qnil)))
3088 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3089 grow_specpdl ();
3090 Fset_default (symbol, value);
3091 return;
3094 else
3095 specpdl_ptr->let.kind = SPECPDL_LET;
3097 grow_specpdl ();
3098 set_internal (symbol, value, Qnil, 1);
3099 break;
3101 default: emacs_abort ();
3105 /* Push unwind-protect entries of various types. */
3107 void
3108 record_unwind_protect (void (*function) (Lisp_Object), Lisp_Object arg)
3110 specpdl_ptr->unwind.kind = SPECPDL_UNWIND;
3111 specpdl_ptr->unwind.func = function;
3112 specpdl_ptr->unwind.arg = arg;
3113 grow_specpdl ();
3116 void
3117 record_unwind_protect_ptr (void (*function) (void *), void *arg)
3119 specpdl_ptr->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3120 specpdl_ptr->unwind_ptr.func = function;
3121 specpdl_ptr->unwind_ptr.arg = arg;
3122 grow_specpdl ();
3125 void
3126 record_unwind_protect_int (void (*function) (int), int arg)
3128 specpdl_ptr->unwind_int.kind = SPECPDL_UNWIND_INT;
3129 specpdl_ptr->unwind_int.func = function;
3130 specpdl_ptr->unwind_int.arg = arg;
3131 grow_specpdl ();
3134 void
3135 record_unwind_protect_void (void (*function) (void))
3137 specpdl_ptr->unwind_void.kind = SPECPDL_UNWIND_VOID;
3138 specpdl_ptr->unwind_void.func = function;
3139 grow_specpdl ();
3142 static void
3143 do_nothing (void)
3146 /* Push an unwind-protect entry that does nothing, so that
3147 set_unwind_protect_ptr can overwrite it later. */
3149 void
3150 record_unwind_protect_nothing (void)
3152 record_unwind_protect_void (do_nothing);
3155 /* Clear the unwind-protect entry COUNT, so that it does nothing.
3156 It need not be at the top of the stack. */
3158 void
3159 clear_unwind_protect (ptrdiff_t count)
3161 union specbinding *p = specpdl + count;
3162 p->unwind_void.kind = SPECPDL_UNWIND_VOID;
3163 p->unwind_void.func = do_nothing;
3166 /* Set the unwind-protect entry COUNT so that it invokes FUNC (ARG).
3167 It need not be at the top of the stack. Discard the entry's
3168 previous value without invoking it. */
3170 void
3171 set_unwind_protect (ptrdiff_t count, void (*func) (Lisp_Object),
3172 Lisp_Object arg)
3174 union specbinding *p = specpdl + count;
3175 p->unwind.kind = SPECPDL_UNWIND;
3176 p->unwind.func = func;
3177 p->unwind.arg = arg;
3180 void
3181 set_unwind_protect_ptr (ptrdiff_t count, void (*func) (void *), void *arg)
3183 union specbinding *p = specpdl + count;
3184 p->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3185 p->unwind_ptr.func = func;
3186 p->unwind_ptr.arg = arg;
3189 /* Pop and execute entries from the unwind-protect stack until the
3190 depth COUNT is reached. Return VALUE. */
3192 Lisp_Object
3193 unbind_to (ptrdiff_t count, Lisp_Object value)
3195 Lisp_Object quitf = Vquit_flag;
3196 struct gcpro gcpro1, gcpro2;
3198 GCPRO2 (value, quitf);
3199 Vquit_flag = Qnil;
3201 while (specpdl_ptr != specpdl + count)
3203 /* Decrement specpdl_ptr before we do the work to unbind it, so
3204 that an error in unbinding won't try to unbind the same entry
3205 again. Take care to copy any parts of the binding needed
3206 before invoking any code that can make more bindings. */
3208 specpdl_ptr--;
3210 switch (specpdl_ptr->kind)
3212 case SPECPDL_UNWIND:
3213 specpdl_ptr->unwind.func (specpdl_ptr->unwind.arg);
3214 break;
3215 case SPECPDL_UNWIND_PTR:
3216 specpdl_ptr->unwind_ptr.func (specpdl_ptr->unwind_ptr.arg);
3217 break;
3218 case SPECPDL_UNWIND_INT:
3219 specpdl_ptr->unwind_int.func (specpdl_ptr->unwind_int.arg);
3220 break;
3221 case SPECPDL_UNWIND_VOID:
3222 specpdl_ptr->unwind_void.func ();
3223 break;
3224 case SPECPDL_BACKTRACE:
3225 break;
3226 case SPECPDL_LET:
3227 { /* If variable has a trivial value (no forwarding), we can
3228 just set it. No need to check for constant symbols here,
3229 since that was already done by specbind. */
3230 struct Lisp_Symbol *sym = XSYMBOL (specpdl_symbol (specpdl_ptr));
3231 if (sym->redirect == SYMBOL_PLAINVAL)
3233 SET_SYMBOL_VAL (sym, specpdl_old_value (specpdl_ptr));
3234 break;
3236 else
3237 { /* FALLTHROUGH!!
3238 NOTE: we only ever come here if make_local_foo was used for
3239 the first time on this var within this let. */
3242 case SPECPDL_LET_DEFAULT:
3243 Fset_default (specpdl_symbol (specpdl_ptr),
3244 specpdl_old_value (specpdl_ptr));
3245 break;
3246 case SPECPDL_LET_LOCAL:
3248 Lisp_Object symbol = specpdl_symbol (specpdl_ptr);
3249 Lisp_Object where = specpdl_where (specpdl_ptr);
3250 Lisp_Object old_value = specpdl_old_value (specpdl_ptr);
3251 eassert (BUFFERP (where));
3253 /* If this was a local binding, reset the value in the appropriate
3254 buffer, but only if that buffer's binding still exists. */
3255 if (!NILP (Flocal_variable_p (symbol, where)))
3256 set_internal (symbol, old_value, where, 1);
3258 break;
3262 if (NILP (Vquit_flag) && !NILP (quitf))
3263 Vquit_flag = quitf;
3265 UNGCPRO;
3266 return value;
3269 DEFUN ("special-variable-p", Fspecial_variable_p, Sspecial_variable_p, 1, 1, 0,
3270 doc: /* Return non-nil if SYMBOL's global binding has been declared special.
3271 A special variable is one that will be bound dynamically, even in a
3272 context where binding is lexical by default. */)
3273 (Lisp_Object symbol)
3275 CHECK_SYMBOL (symbol);
3276 return XSYMBOL (symbol)->declared_special ? Qt : Qnil;
3280 DEFUN ("backtrace-debug", Fbacktrace_debug, Sbacktrace_debug, 2, 2, 0,
3281 doc: /* Set the debug-on-exit flag of eval frame LEVEL levels down to FLAG.
3282 The debugger is entered when that frame exits, if the flag is non-nil. */)
3283 (Lisp_Object level, Lisp_Object flag)
3285 union specbinding *pdl = backtrace_top ();
3286 register EMACS_INT i;
3288 CHECK_NUMBER (level);
3290 for (i = 0; backtrace_p (pdl) && i < XINT (level); i++)
3291 pdl = backtrace_next (pdl);
3293 if (backtrace_p (pdl))
3294 set_backtrace_debug_on_exit (pdl, !NILP (flag));
3296 return flag;
3299 DEFUN ("backtrace", Fbacktrace, Sbacktrace, 0, 0, "",
3300 doc: /* Print a trace of Lisp function calls currently active.
3301 Output stream used is value of `standard-output'. */)
3302 (void)
3304 union specbinding *pdl = backtrace_top ();
3305 Lisp_Object tem;
3306 Lisp_Object old_print_level = Vprint_level;
3308 if (NILP (Vprint_level))
3309 XSETFASTINT (Vprint_level, 8);
3311 while (backtrace_p (pdl))
3313 write_string (backtrace_debug_on_exit (pdl) ? "* " : " ", 2);
3314 if (backtrace_nargs (pdl) == UNEVALLED)
3316 Fprin1 (Fcons (backtrace_function (pdl), *backtrace_args (pdl)),
3317 Qnil);
3318 write_string ("\n", -1);
3320 else
3322 tem = backtrace_function (pdl);
3323 Fprin1 (tem, Qnil); /* This can QUIT. */
3324 write_string ("(", -1);
3326 ptrdiff_t i;
3327 for (i = 0; i < backtrace_nargs (pdl); i++)
3329 if (i) write_string (" ", -1);
3330 Fprin1 (backtrace_args (pdl)[i], Qnil);
3333 write_string (")\n", -1);
3335 pdl = backtrace_next (pdl);
3338 Vprint_level = old_print_level;
3339 return Qnil;
3342 static union specbinding *
3343 get_backtrace_frame (Lisp_Object nframes, Lisp_Object base)
3345 union specbinding *pdl = backtrace_top ();
3346 register EMACS_INT i;
3348 CHECK_NATNUM (nframes);
3350 if (!NILP (base))
3351 { /* Skip up to `base'. */
3352 base = Findirect_function (base, Qt);
3353 while (backtrace_p (pdl)
3354 && !EQ (base, Findirect_function (backtrace_function (pdl), Qt)))
3355 pdl = backtrace_next (pdl);
3358 /* Find the frame requested. */
3359 for (i = XFASTINT (nframes); i > 0 && backtrace_p (pdl); i--)
3360 pdl = backtrace_next (pdl);
3362 return pdl;
3365 DEFUN ("backtrace-frame", Fbacktrace_frame, Sbacktrace_frame, 1, 2, NULL,
3366 doc: /* Return the function and arguments NFRAMES up from current execution point.
3367 If that frame has not evaluated the arguments yet (or is a special form),
3368 the value is (nil FUNCTION ARG-FORMS...).
3369 If that frame has evaluated its arguments and called its function already,
3370 the value is (t FUNCTION ARG-VALUES...).
3371 A &rest arg is represented as the tail of the list ARG-VALUES.
3372 FUNCTION is whatever was supplied as car of evaluated list,
3373 or a lambda expression for macro calls.
3374 If NFRAMES is more than the number of frames, the value is nil.
3375 If BASE is non-nil, it should be a function and NFRAMES counts from its
3376 nearest activation frame. */)
3377 (Lisp_Object nframes, Lisp_Object base)
3379 union specbinding *pdl = get_backtrace_frame (nframes, base);
3381 if (!backtrace_p (pdl))
3382 return Qnil;
3383 if (backtrace_nargs (pdl) == UNEVALLED)
3384 return Fcons (Qnil,
3385 Fcons (backtrace_function (pdl), *backtrace_args (pdl)));
3386 else
3388 Lisp_Object tem = Flist (backtrace_nargs (pdl), backtrace_args (pdl));
3390 return Fcons (Qt, Fcons (backtrace_function (pdl), tem));
3394 /* For backtrace-eval, we want to temporarily unwind the last few elements of
3395 the specpdl stack, and then rewind them. We store the pre-unwind values
3396 directly in the pre-existing specpdl elements (i.e. we swap the current
3397 value and the old value stored in the specpdl), kind of like the inplace
3398 pointer-reversal trick. As it turns out, the rewind does the same as the
3399 unwind, except it starts from the other end of the specpdl stack, so we use
3400 the same function for both unwind and rewind. */
3401 static void
3402 backtrace_eval_unrewind (int distance)
3404 union specbinding *tmp = specpdl_ptr;
3405 int step = -1;
3406 if (distance < 0)
3407 { /* It's a rewind rather than unwind. */
3408 tmp += distance - 1;
3409 step = 1;
3410 distance = -distance;
3413 for (; distance > 0; distance--)
3415 tmp += step;
3416 /* */
3417 switch (tmp->kind)
3419 /* FIXME: Ideally we'd like to "temporarily unwind" (some of) those
3420 unwind_protect, but the problem is that we don't know how to
3421 rewind them afterwards. */
3422 case SPECPDL_UNWIND:
3423 case SPECPDL_UNWIND_PTR:
3424 case SPECPDL_UNWIND_INT:
3425 case SPECPDL_UNWIND_VOID:
3426 case SPECPDL_BACKTRACE:
3427 break;
3428 case SPECPDL_LET:
3429 { /* If variable has a trivial value (no forwarding), we can
3430 just set it. No need to check for constant symbols here,
3431 since that was already done by specbind. */
3432 struct Lisp_Symbol *sym = XSYMBOL (specpdl_symbol (tmp));
3433 if (sym->redirect == SYMBOL_PLAINVAL)
3435 Lisp_Object old_value = specpdl_old_value (tmp);
3436 set_specpdl_old_value (tmp, SYMBOL_VAL (sym));
3437 SET_SYMBOL_VAL (sym, old_value);
3438 break;
3440 else
3441 { /* FALLTHROUGH!!
3442 NOTE: we only ever come here if make_local_foo was used for
3443 the first time on this var within this let. */
3446 case SPECPDL_LET_DEFAULT:
3448 Lisp_Object sym = specpdl_symbol (tmp);
3449 Lisp_Object old_value = specpdl_old_value (tmp);
3450 set_specpdl_old_value (tmp, Fdefault_value (sym));
3451 Fset_default (sym, old_value);
3453 break;
3454 case SPECPDL_LET_LOCAL:
3456 Lisp_Object symbol = specpdl_symbol (tmp);
3457 Lisp_Object where = specpdl_where (tmp);
3458 Lisp_Object old_value = specpdl_old_value (tmp);
3459 eassert (BUFFERP (where));
3461 /* If this was a local binding, reset the value in the appropriate
3462 buffer, but only if that buffer's binding still exists. */
3463 if (!NILP (Flocal_variable_p (symbol, where)))
3465 set_specpdl_old_value
3466 (tmp, Fbuffer_local_value (symbol, where));
3467 set_internal (symbol, old_value, where, 1);
3470 break;
3475 DEFUN ("backtrace-eval", Fbacktrace_eval, Sbacktrace_eval, 2, 3, NULL,
3476 doc: /* Evaluate EXP in the context of some activation frame.
3477 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3478 (Lisp_Object exp, Lisp_Object nframes, Lisp_Object base)
3480 union specbinding *pdl = get_backtrace_frame (nframes, base);
3481 ptrdiff_t count = SPECPDL_INDEX ();
3482 ptrdiff_t distance = specpdl_ptr - pdl;
3483 eassert (distance >= 0);
3485 if (!backtrace_p (pdl))
3486 error ("Activation frame not found!");
3488 backtrace_eval_unrewind (distance);
3489 record_unwind_protect_int (backtrace_eval_unrewind, -distance);
3491 /* Use eval_sub rather than Feval since the main motivation behind
3492 backtrace-eval is to be able to get/set the value of lexical variables
3493 from the debugger. */
3494 return unbind_to (count, eval_sub (exp));
3497 DEFUN ("backtrace--locals", Fbacktrace__locals, Sbacktrace__locals, 1, 2, NULL,
3498 doc: /* Return names and values of local variables of a stack frame.
3499 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3500 (Lisp_Object nframes, Lisp_Object base)
3502 union specbinding *frame = get_backtrace_frame (nframes, base);
3503 union specbinding *prevframe
3504 = get_backtrace_frame (make_number (XFASTINT (nframes) - 1), base);
3505 ptrdiff_t distance = specpdl_ptr - frame;
3506 Lisp_Object result = Qnil;
3507 eassert (distance >= 0);
3509 if (!backtrace_p (prevframe))
3510 error ("Activation frame not found!");
3511 if (!backtrace_p (frame))
3512 error ("Activation frame not found!");
3514 /* The specpdl entries normally contain the symbol being bound along with its
3515 `old_value', so it can be restored. The new value to which it is bound is
3516 available in one of two places: either in the current value of the
3517 variable (if it hasn't been rebound yet) or in the `old_value' slot of the
3518 next specpdl entry for it.
3519 `backtrace_eval_unrewind' happens to swap the role of `old_value'
3520 and "new value", so we abuse it here, to fetch the new value.
3521 It's ugly (we'd rather not modify global data) and a bit inefficient,
3522 but it does the job for now. */
3523 backtrace_eval_unrewind (distance);
3525 /* Grab values. */
3527 union specbinding *tmp = prevframe;
3528 for (; tmp > frame; tmp--)
3530 switch (tmp->kind)
3532 case SPECPDL_LET:
3533 case SPECPDL_LET_DEFAULT:
3534 case SPECPDL_LET_LOCAL:
3536 Lisp_Object sym = specpdl_symbol (tmp);
3537 Lisp_Object val = specpdl_old_value (tmp);
3538 if (EQ (sym, Qinternal_interpreter_environment))
3540 Lisp_Object env = val;
3541 for (; CONSP (env); env = XCDR (env))
3543 Lisp_Object binding = XCAR (env);
3544 if (CONSP (binding))
3545 result = Fcons (Fcons (XCAR (binding),
3546 XCDR (binding)),
3547 result);
3550 else
3551 result = Fcons (Fcons (sym, val), result);
3557 /* Restore values from specpdl to original place. */
3558 backtrace_eval_unrewind (-distance);
3560 return result;
3564 void
3565 mark_specpdl (void)
3567 union specbinding *pdl;
3568 for (pdl = specpdl; pdl != specpdl_ptr; pdl++)
3570 switch (pdl->kind)
3572 case SPECPDL_UNWIND:
3573 mark_object (specpdl_arg (pdl));
3574 break;
3576 case SPECPDL_BACKTRACE:
3578 ptrdiff_t nargs = backtrace_nargs (pdl);
3579 mark_object (backtrace_function (pdl));
3580 if (nargs == UNEVALLED)
3581 nargs = 1;
3582 while (nargs--)
3583 mark_object (backtrace_args (pdl)[nargs]);
3585 break;
3587 case SPECPDL_LET_DEFAULT:
3588 case SPECPDL_LET_LOCAL:
3589 mark_object (specpdl_where (pdl));
3590 /* Fall through. */
3591 case SPECPDL_LET:
3592 mark_object (specpdl_symbol (pdl));
3593 mark_object (specpdl_old_value (pdl));
3594 break;
3599 void
3600 get_backtrace (Lisp_Object array)
3602 union specbinding *pdl = backtrace_next (backtrace_top ());
3603 ptrdiff_t i = 0, asize = ASIZE (array);
3605 /* Copy the backtrace contents into working memory. */
3606 for (; i < asize; i++)
3608 if (backtrace_p (pdl))
3610 ASET (array, i, backtrace_function (pdl));
3611 pdl = backtrace_next (pdl);
3613 else
3614 ASET (array, i, Qnil);
3618 Lisp_Object backtrace_top_function (void)
3620 union specbinding *pdl = backtrace_top ();
3621 return (backtrace_p (pdl) ? backtrace_function (pdl) : Qnil);
3624 void
3625 syms_of_eval (void)
3627 DEFVAR_INT ("max-specpdl-size", max_specpdl_size,
3628 doc: /* Limit on number of Lisp variable bindings and `unwind-protect's.
3629 If Lisp code tries to increase the total number past this amount,
3630 an error is signaled.
3631 You can safely use a value considerably larger than the default value,
3632 if that proves inconveniently small. However, if you increase it too far,
3633 Emacs could run out of memory trying to make the stack bigger.
3634 Note that this limit may be silently increased by the debugger
3635 if `debug-on-error' or `debug-on-quit' is set. */);
3637 DEFVAR_INT ("max-lisp-eval-depth", max_lisp_eval_depth,
3638 doc: /* Limit on depth in `eval', `apply' and `funcall' before error.
3640 This limit serves to catch infinite recursions for you before they cause
3641 actual stack overflow in C, which would be fatal for Emacs.
3642 You can safely make it considerably larger than its default value,
3643 if that proves inconveniently small. However, if you increase it too far,
3644 Emacs could overflow the real C stack, and crash. */);
3646 DEFVAR_LISP ("quit-flag", Vquit_flag,
3647 doc: /* Non-nil causes `eval' to abort, unless `inhibit-quit' is non-nil.
3648 If the value is t, that means do an ordinary quit.
3649 If the value equals `throw-on-input', that means quit by throwing
3650 to the tag specified in `throw-on-input'; it's for handling `while-no-input'.
3651 Typing C-g sets `quit-flag' to t, regardless of `inhibit-quit',
3652 but `inhibit-quit' non-nil prevents anything from taking notice of that. */);
3653 Vquit_flag = Qnil;
3655 DEFVAR_LISP ("inhibit-quit", Vinhibit_quit,
3656 doc: /* Non-nil inhibits C-g quitting from happening immediately.
3657 Note that `quit-flag' will still be set by typing C-g,
3658 so a quit will be signaled as soon as `inhibit-quit' is nil.
3659 To prevent this happening, set `quit-flag' to nil
3660 before making `inhibit-quit' nil. */);
3661 Vinhibit_quit = Qnil;
3663 DEFSYM (Qinhibit_quit, "inhibit-quit");
3664 DEFSYM (Qautoload, "autoload");
3665 DEFSYM (Qinhibit_debugger, "inhibit-debugger");
3666 DEFSYM (Qmacro, "macro");
3667 DEFSYM (Qdeclare, "declare");
3669 /* Note that the process handling also uses Qexit, but we don't want
3670 to staticpro it twice, so we just do it here. */
3671 DEFSYM (Qexit, "exit");
3673 DEFSYM (Qinteractive, "interactive");
3674 DEFSYM (Qcommandp, "commandp");
3675 DEFSYM (Qand_rest, "&rest");
3676 DEFSYM (Qand_optional, "&optional");
3677 DEFSYM (Qclosure, "closure");
3678 DEFSYM (Qdebug, "debug");
3680 DEFVAR_LISP ("inhibit-debugger", Vinhibit_debugger,
3681 doc: /* Non-nil means never enter the debugger.
3682 Normally set while the debugger is already active, to avoid recursive
3683 invocations. */);
3684 Vinhibit_debugger = Qnil;
3686 DEFVAR_LISP ("debug-on-error", Vdebug_on_error,
3687 doc: /* Non-nil means enter debugger if an error is signaled.
3688 Does not apply to errors handled by `condition-case' or those
3689 matched by `debug-ignored-errors'.
3690 If the value is a list, an error only means to enter the debugger
3691 if one of its condition symbols appears in the list.
3692 When you evaluate an expression interactively, this variable
3693 is temporarily non-nil if `eval-expression-debug-on-error' is non-nil.
3694 The command `toggle-debug-on-error' toggles this.
3695 See also the variable `debug-on-quit' and `inhibit-debugger'. */);
3696 Vdebug_on_error = Qnil;
3698 DEFVAR_LISP ("debug-ignored-errors", Vdebug_ignored_errors,
3699 doc: /* List of errors for which the debugger should not be called.
3700 Each element may be a condition-name or a regexp that matches error messages.
3701 If any element applies to a given error, that error skips the debugger
3702 and just returns to top level.
3703 This overrides the variable `debug-on-error'.
3704 It does not apply to errors handled by `condition-case'. */);
3705 Vdebug_ignored_errors = Qnil;
3707 DEFVAR_BOOL ("debug-on-quit", debug_on_quit,
3708 doc: /* Non-nil means enter debugger if quit is signaled (C-g, for example).
3709 Does not apply if quit is handled by a `condition-case'. */);
3710 debug_on_quit = 0;
3712 DEFVAR_BOOL ("debug-on-next-call", debug_on_next_call,
3713 doc: /* Non-nil means enter debugger before next `eval', `apply' or `funcall'. */);
3715 DEFVAR_BOOL ("debugger-may-continue", debugger_may_continue,
3716 doc: /* Non-nil means debugger may continue execution.
3717 This is nil when the debugger is called under circumstances where it
3718 might not be safe to continue. */);
3719 debugger_may_continue = 1;
3721 DEFVAR_LISP ("debugger", Vdebugger,
3722 doc: /* Function to call to invoke debugger.
3723 If due to frame exit, args are `exit' and the value being returned;
3724 this function's value will be returned instead of that.
3725 If due to error, args are `error' and a list of the args to `signal'.
3726 If due to `apply' or `funcall' entry, one arg, `lambda'.
3727 If due to `eval' entry, one arg, t. */);
3728 Vdebugger = Qnil;
3730 DEFVAR_LISP ("signal-hook-function", Vsignal_hook_function,
3731 doc: /* If non-nil, this is a function for `signal' to call.
3732 It receives the same arguments that `signal' was given.
3733 The Edebug package uses this to regain control. */);
3734 Vsignal_hook_function = Qnil;
3736 DEFVAR_LISP ("debug-on-signal", Vdebug_on_signal,
3737 doc: /* Non-nil means call the debugger regardless of condition handlers.
3738 Note that `debug-on-error', `debug-on-quit' and friends
3739 still determine whether to handle the particular condition. */);
3740 Vdebug_on_signal = Qnil;
3742 /* When lexical binding is being used,
3743 Vinternal_interpreter_environment is non-nil, and contains an alist
3744 of lexically-bound variable, or (t), indicating an empty
3745 environment. The lisp name of this variable would be
3746 `internal-interpreter-environment' if it weren't hidden.
3747 Every element of this list can be either a cons (VAR . VAL)
3748 specifying a lexical binding, or a single symbol VAR indicating
3749 that this variable should use dynamic scoping. */
3750 DEFSYM (Qinternal_interpreter_environment,
3751 "internal-interpreter-environment");
3752 DEFVAR_LISP ("internal-interpreter-environment",
3753 Vinternal_interpreter_environment,
3754 doc: /* If non-nil, the current lexical environment of the lisp interpreter.
3755 When lexical binding is not being used, this variable is nil.
3756 A value of `(t)' indicates an empty environment, otherwise it is an
3757 alist of active lexical bindings. */);
3758 Vinternal_interpreter_environment = Qnil;
3759 /* Don't export this variable to Elisp, so no one can mess with it
3760 (Just imagine if someone makes it buffer-local). */
3761 Funintern (Qinternal_interpreter_environment, Qnil);
3763 DEFSYM (Vrun_hooks, "run-hooks");
3765 staticpro (&Vautoload_queue);
3766 Vautoload_queue = Qnil;
3767 staticpro (&Vsignaling_function);
3768 Vsignaling_function = Qnil;
3770 inhibit_lisp_code = Qnil;
3772 defsubr (&Sor);
3773 defsubr (&Sand);
3774 defsubr (&Sif);
3775 defsubr (&Scond);
3776 defsubr (&Sprogn);
3777 defsubr (&Sprog1);
3778 defsubr (&Sprog2);
3779 defsubr (&Ssetq);
3780 defsubr (&Squote);
3781 defsubr (&Sfunction);
3782 defsubr (&Sdefault_toplevel_value);
3783 defsubr (&Sset_default_toplevel_value);
3784 defsubr (&Sdefvar);
3785 defsubr (&Sdefvaralias);
3786 defsubr (&Sdefconst);
3787 defsubr (&Smake_var_non_special);
3788 defsubr (&Slet);
3789 defsubr (&SletX);
3790 defsubr (&Swhile);
3791 defsubr (&Smacroexpand);
3792 defsubr (&Scatch);
3793 defsubr (&Sthrow);
3794 defsubr (&Sunwind_protect);
3795 defsubr (&Scondition_case);
3796 defsubr (&Ssignal);
3797 defsubr (&Scommandp);
3798 defsubr (&Sautoload);
3799 defsubr (&Sautoload_do_load);
3800 defsubr (&Seval);
3801 defsubr (&Sapply);
3802 defsubr (&Sfuncall);
3803 defsubr (&Srun_hooks);
3804 defsubr (&Srun_hook_with_args);
3805 defsubr (&Srun_hook_with_args_until_success);
3806 defsubr (&Srun_hook_with_args_until_failure);
3807 defsubr (&Srun_hook_wrapped);
3808 defsubr (&Sfetch_bytecode);
3809 defsubr (&Sbacktrace_debug);
3810 defsubr (&Sbacktrace);
3811 defsubr (&Sbacktrace_frame);
3812 defsubr (&Sbacktrace_eval);
3813 defsubr (&Sbacktrace__locals);
3814 defsubr (&Sspecial_variable_p);
3815 defsubr (&Sfunctionp);