Remove interpreter’s byte stack
[emacs.git] / src / eval.c
blobf681ef7c2789acfa2dac43ee20f357dfe64d141c
1 /* Evaluator for GNU Emacs Lisp interpreter.
3 Copyright (C) 1985-1987, 1993-1995, 1999-2016 Free Software Foundation,
4 Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
23 #include <limits.h>
24 #include <stdio.h>
25 #include "lisp.h"
26 #include "blockinput.h"
27 #include "commands.h"
28 #include "keyboard.h"
29 #include "dispextern.h"
30 #include "buffer.h"
32 /* Chain of condition and catch handlers currently in effect. */
34 struct handler *handlerlist;
36 /* Non-nil means record all fset's and provide's, to be undone
37 if the file being autoloaded is not fully loaded.
38 They are recorded by being consed onto the front of Vautoload_queue:
39 (FUN . ODEF) for a defun, (0 . OFEATURES) for a provide. */
41 Lisp_Object Vautoload_queue;
43 /* This holds either the symbol `run-hooks' or nil.
44 It is nil at an early stage of startup, and when Emacs
45 is shutting down. */
46 Lisp_Object Vrun_hooks;
48 /* Current number of specbindings allocated in specpdl, not counting
49 the dummy entry specpdl[-1]. */
51 ptrdiff_t specpdl_size;
53 /* Pointer to beginning of specpdl. A dummy entry specpdl[-1] exists
54 only so that its address can be taken. */
56 union specbinding *specpdl;
58 /* Pointer to first unused element in specpdl. */
60 union specbinding *specpdl_ptr;
62 /* Depth in Lisp evaluations and function calls. */
64 static EMACS_INT lisp_eval_depth;
66 /* The value of num_nonmacro_input_events as of the last time we
67 started to enter the debugger. If we decide to enter the debugger
68 again when this is still equal to num_nonmacro_input_events, then we
69 know that the debugger itself has an error, and we should just
70 signal the error instead of entering an infinite loop of debugger
71 invocations. */
73 static EMACS_INT when_entered_debugger;
75 /* The function from which the last `signal' was called. Set in
76 Fsignal. */
77 /* FIXME: We should probably get rid of this! */
78 Lisp_Object Vsignaling_function;
80 /* If non-nil, Lisp code must not be run since some part of Emacs is in
81 an inconsistent state. Currently unused. */
82 Lisp_Object inhibit_lisp_code;
84 /* These would ordinarily be static, but they need to be visible to GDB. */
85 bool backtrace_p (union specbinding *) EXTERNALLY_VISIBLE;
86 Lisp_Object *backtrace_args (union specbinding *) EXTERNALLY_VISIBLE;
87 Lisp_Object backtrace_function (union specbinding *) EXTERNALLY_VISIBLE;
88 union specbinding *backtrace_next (union specbinding *) EXTERNALLY_VISIBLE;
89 union specbinding *backtrace_top (void) EXTERNALLY_VISIBLE;
91 static Lisp_Object funcall_lambda (Lisp_Object, ptrdiff_t, Lisp_Object *);
92 static Lisp_Object apply_lambda (Lisp_Object, Lisp_Object, ptrdiff_t);
93 static Lisp_Object lambda_arity (Lisp_Object);
95 static Lisp_Object
96 specpdl_symbol (union specbinding *pdl)
98 eassert (pdl->kind >= SPECPDL_LET);
99 return pdl->let.symbol;
102 static Lisp_Object
103 specpdl_old_value (union specbinding *pdl)
105 eassert (pdl->kind >= SPECPDL_LET);
106 return pdl->let.old_value;
109 static void
110 set_specpdl_old_value (union specbinding *pdl, Lisp_Object val)
112 eassert (pdl->kind >= SPECPDL_LET);
113 pdl->let.old_value = val;
116 static Lisp_Object
117 specpdl_where (union specbinding *pdl)
119 eassert (pdl->kind > SPECPDL_LET);
120 return pdl->let.where;
123 static Lisp_Object
124 specpdl_arg (union specbinding *pdl)
126 eassert (pdl->kind == SPECPDL_UNWIND);
127 return pdl->unwind.arg;
130 Lisp_Object
131 backtrace_function (union specbinding *pdl)
133 eassert (pdl->kind == SPECPDL_BACKTRACE);
134 return pdl->bt.function;
137 static ptrdiff_t
138 backtrace_nargs (union specbinding *pdl)
140 eassert (pdl->kind == SPECPDL_BACKTRACE);
141 return pdl->bt.nargs;
144 Lisp_Object *
145 backtrace_args (union specbinding *pdl)
147 eassert (pdl->kind == SPECPDL_BACKTRACE);
148 return pdl->bt.args;
151 static bool
152 backtrace_debug_on_exit (union specbinding *pdl)
154 eassert (pdl->kind == SPECPDL_BACKTRACE);
155 return pdl->bt.debug_on_exit;
158 /* Functions to modify slots of backtrace records. */
160 static void
161 set_backtrace_args (union specbinding *pdl, Lisp_Object *args, ptrdiff_t nargs)
163 eassert (pdl->kind == SPECPDL_BACKTRACE);
164 pdl->bt.args = args;
165 pdl->bt.nargs = nargs;
168 static void
169 set_backtrace_debug_on_exit (union specbinding *pdl, bool doe)
171 eassert (pdl->kind == SPECPDL_BACKTRACE);
172 pdl->bt.debug_on_exit = doe;
175 /* Helper functions to scan the backtrace. */
177 bool
178 backtrace_p (union specbinding *pdl)
179 { return pdl >= specpdl; }
181 union specbinding *
182 backtrace_top (void)
184 union specbinding *pdl = specpdl_ptr - 1;
185 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
186 pdl--;
187 return pdl;
190 union specbinding *
191 backtrace_next (union specbinding *pdl)
193 pdl--;
194 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
195 pdl--;
196 return pdl;
199 /* Return a pointer to somewhere near the top of the C stack. */
200 void *
201 near_C_stack_top (void)
203 return backtrace_args (backtrace_top ());
206 void
207 init_eval_once (void)
209 enum { size = 50 };
210 union specbinding *pdlvec = xmalloc ((size + 1) * sizeof *specpdl);
211 specpdl_size = size;
212 specpdl = specpdl_ptr = pdlvec + 1;
213 /* Don't forget to update docs (lispref node "Local Variables"). */
214 max_specpdl_size = 1300; /* 1000 is not enough for CEDET's c-by.el. */
215 max_lisp_eval_depth = 800;
217 Vrun_hooks = Qnil;
220 static struct handler handlerlist_sentinel;
222 void
223 init_eval (void)
225 specpdl_ptr = specpdl;
226 { /* Put a dummy catcher at top-level so that handlerlist is never NULL.
227 This is important since handlerlist->nextfree holds the freelist
228 which would otherwise leak every time we unwind back to top-level. */
229 handlerlist = handlerlist_sentinel.nextfree = &handlerlist_sentinel;
230 struct handler *c = push_handler (Qunbound, CATCHER);
231 eassert (c == &handlerlist_sentinel);
232 handlerlist_sentinel.nextfree = NULL;
233 handlerlist_sentinel.next = NULL;
235 Vquit_flag = Qnil;
236 debug_on_next_call = 0;
237 lisp_eval_depth = 0;
238 /* This is less than the initial value of num_nonmacro_input_events. */
239 when_entered_debugger = -1;
242 /* Unwind-protect function used by call_debugger. */
244 static void
245 restore_stack_limits (Lisp_Object data)
247 max_specpdl_size = XINT (XCAR (data));
248 max_lisp_eval_depth = XINT (XCDR (data));
251 static void grow_specpdl (void);
253 /* Call the Lisp debugger, giving it argument ARG. */
255 Lisp_Object
256 call_debugger (Lisp_Object arg)
258 bool debug_while_redisplaying;
259 ptrdiff_t count = SPECPDL_INDEX ();
260 Lisp_Object val;
261 EMACS_INT old_depth = max_lisp_eval_depth;
262 /* Do not allow max_specpdl_size less than actual depth (Bug#16603). */
263 EMACS_INT old_max = max (max_specpdl_size, count);
265 if (lisp_eval_depth + 40 > max_lisp_eval_depth)
266 max_lisp_eval_depth = lisp_eval_depth + 40;
268 /* While debugging Bug#16603, previous value of 100 was found
269 too small to avoid specpdl overflow in the debugger itself. */
270 if (max_specpdl_size - 200 < count)
271 max_specpdl_size = count + 200;
273 if (old_max == count)
275 /* We can enter the debugger due to specpdl overflow (Bug#16603). */
276 specpdl_ptr--;
277 grow_specpdl ();
280 /* Restore limits after leaving the debugger. */
281 record_unwind_protect (restore_stack_limits,
282 Fcons (make_number (old_max),
283 make_number (old_depth)));
285 #ifdef HAVE_WINDOW_SYSTEM
286 if (display_hourglass_p)
287 cancel_hourglass ();
288 #endif
290 debug_on_next_call = 0;
291 when_entered_debugger = num_nonmacro_input_events;
293 /* Resetting redisplaying_p to 0 makes sure that debug output is
294 displayed if the debugger is invoked during redisplay. */
295 debug_while_redisplaying = redisplaying_p;
296 redisplaying_p = 0;
297 specbind (intern ("debugger-may-continue"),
298 debug_while_redisplaying ? Qnil : Qt);
299 specbind (Qinhibit_redisplay, Qnil);
300 specbind (Qinhibit_debugger, Qt);
302 /* If we are debugging an error while `inhibit-changing-match-data'
303 is bound to non-nil (e.g., within a call to `string-match-p'),
304 then make sure debugger code can still use match data. */
305 specbind (Qinhibit_changing_match_data, Qnil);
307 #if 0 /* Binding this prevents execution of Lisp code during
308 redisplay, which necessarily leads to display problems. */
309 specbind (Qinhibit_eval_during_redisplay, Qt);
310 #endif
312 val = apply1 (Vdebugger, arg);
314 /* Interrupting redisplay and resuming it later is not safe under
315 all circumstances. So, when the debugger returns, abort the
316 interrupted redisplay by going back to the top-level. */
317 if (debug_while_redisplaying)
318 Ftop_level ();
320 return unbind_to (count, val);
323 static void
324 do_debug_on_call (Lisp_Object code, ptrdiff_t count)
326 debug_on_next_call = 0;
327 set_backtrace_debug_on_exit (specpdl + count, true);
328 call_debugger (list1 (code));
331 /* NOTE!!! Every function that can call EVAL must protect its args
332 and temporaries from garbage collection while it needs them.
333 The definition of `For' shows what you have to do. */
335 DEFUN ("or", For, Sor, 0, UNEVALLED, 0,
336 doc: /* Eval args until one of them yields non-nil, then return that value.
337 The remaining args are not evalled at all.
338 If all args return nil, return nil.
339 usage: (or CONDITIONS...) */)
340 (Lisp_Object args)
342 Lisp_Object val = Qnil;
344 while (CONSP (args))
346 val = eval_sub (XCAR (args));
347 if (!NILP (val))
348 break;
349 args = XCDR (args);
352 return val;
355 DEFUN ("and", Fand, Sand, 0, UNEVALLED, 0,
356 doc: /* Eval args until one of them yields nil, then return nil.
357 The remaining args are not evalled at all.
358 If no arg yields nil, return the last arg's value.
359 usage: (and CONDITIONS...) */)
360 (Lisp_Object args)
362 Lisp_Object val = Qt;
364 while (CONSP (args))
366 val = eval_sub (XCAR (args));
367 if (NILP (val))
368 break;
369 args = XCDR (args);
372 return val;
375 DEFUN ("if", Fif, Sif, 2, UNEVALLED, 0,
376 doc: /* If COND yields non-nil, do THEN, else do ELSE...
377 Returns the value of THEN or the value of the last of the ELSE's.
378 THEN must be one expression, but ELSE... can be zero or more expressions.
379 If COND yields nil, and there are no ELSE's, the value is nil.
380 usage: (if COND THEN ELSE...) */)
381 (Lisp_Object args)
383 Lisp_Object cond;
385 cond = eval_sub (XCAR (args));
387 if (!NILP (cond))
388 return eval_sub (Fcar (XCDR (args)));
389 return Fprogn (XCDR (XCDR (args)));
392 DEFUN ("cond", Fcond, Scond, 0, UNEVALLED, 0,
393 doc: /* Try each clause until one succeeds.
394 Each clause looks like (CONDITION BODY...). CONDITION is evaluated
395 and, if the value is non-nil, this clause succeeds:
396 then the expressions in BODY are evaluated and the last one's
397 value is the value of the cond-form.
398 If a clause has one element, as in (CONDITION), then the cond-form
399 returns CONDITION's value, if that is non-nil.
400 If no clause succeeds, cond returns nil.
401 usage: (cond CLAUSES...) */)
402 (Lisp_Object args)
404 Lisp_Object val = args;
406 while (CONSP (args))
408 Lisp_Object clause = XCAR (args);
409 val = eval_sub (Fcar (clause));
410 if (!NILP (val))
412 if (!NILP (XCDR (clause)))
413 val = Fprogn (XCDR (clause));
414 break;
416 args = XCDR (args);
419 return val;
422 DEFUN ("progn", Fprogn, Sprogn, 0, UNEVALLED, 0,
423 doc: /* Eval BODY forms sequentially and return value of last one.
424 usage: (progn BODY...) */)
425 (Lisp_Object body)
427 Lisp_Object val = Qnil;
429 while (CONSP (body))
431 val = eval_sub (XCAR (body));
432 body = XCDR (body);
435 return val;
438 /* Evaluate BODY sequentially, discarding its value. Suitable for
439 record_unwind_protect. */
441 void
442 unwind_body (Lisp_Object body)
444 Fprogn (body);
447 DEFUN ("prog1", Fprog1, Sprog1, 1, UNEVALLED, 0,
448 doc: /* Eval FIRST and BODY sequentially; return value from FIRST.
449 The value of FIRST is saved during the evaluation of the remaining args,
450 whose values are discarded.
451 usage: (prog1 FIRST BODY...) */)
452 (Lisp_Object args)
454 Lisp_Object val;
455 Lisp_Object args_left;
457 args_left = args;
458 val = args;
460 val = eval_sub (XCAR (args_left));
461 while (CONSP (args_left = XCDR (args_left)))
462 eval_sub (XCAR (args_left));
464 return val;
467 DEFUN ("prog2", Fprog2, Sprog2, 2, UNEVALLED, 0,
468 doc: /* Eval FORM1, FORM2 and BODY sequentially; return value from FORM2.
469 The value of FORM2 is saved during the evaluation of the
470 remaining args, whose values are discarded.
471 usage: (prog2 FORM1 FORM2 BODY...) */)
472 (Lisp_Object args)
474 eval_sub (XCAR (args));
475 return Fprog1 (XCDR (args));
478 DEFUN ("setq", Fsetq, Ssetq, 0, UNEVALLED, 0,
479 doc: /* Set each SYM to the value of its VAL.
480 The symbols SYM are variables; they are literal (not evaluated).
481 The values VAL are expressions; they are evaluated.
482 Thus, (setq x (1+ y)) sets `x' to the value of `(1+ y)'.
483 The second VAL is not computed until after the first SYM is set, and so on;
484 each VAL can use the new value of variables set earlier in the `setq'.
485 The return value of the `setq' form is the value of the last VAL.
486 usage: (setq [SYM VAL]...) */)
487 (Lisp_Object args)
489 Lisp_Object val, sym, lex_binding;
491 val = args;
492 if (CONSP (args))
494 Lisp_Object args_left = args;
495 Lisp_Object numargs = Flength (args);
497 if (XINT (numargs) & 1)
498 xsignal2 (Qwrong_number_of_arguments, Qsetq, numargs);
502 val = eval_sub (Fcar (XCDR (args_left)));
503 sym = XCAR (args_left);
505 /* Like for eval_sub, we do not check declared_special here since
506 it's been done when let-binding. */
507 if (!NILP (Vinternal_interpreter_environment) /* Mere optimization! */
508 && SYMBOLP (sym)
509 && !NILP (lex_binding
510 = Fassq (sym, Vinternal_interpreter_environment)))
511 XSETCDR (lex_binding, val); /* SYM is lexically bound. */
512 else
513 Fset (sym, val); /* SYM is dynamically bound. */
515 args_left = Fcdr (XCDR (args_left));
517 while (CONSP (args_left));
520 return val;
523 DEFUN ("quote", Fquote, Squote, 1, UNEVALLED, 0,
524 doc: /* Return the argument, without evaluating it. `(quote x)' yields `x'.
525 Warning: `quote' does not construct its return value, but just returns
526 the value that was pre-constructed by the Lisp reader (see info node
527 `(elisp)Printed Representation').
528 This means that \\='(a . b) is not identical to (cons \\='a \\='b): the former
529 does not cons. Quoting should be reserved for constants that will
530 never be modified by side-effects, unless you like self-modifying code.
531 See the common pitfall in info node `(elisp)Rearrangement' for an example
532 of unexpected results when a quoted object is modified.
533 usage: (quote ARG) */)
534 (Lisp_Object args)
536 if (CONSP (XCDR (args)))
537 xsignal2 (Qwrong_number_of_arguments, Qquote, Flength (args));
538 return XCAR (args);
541 DEFUN ("function", Ffunction, Sfunction, 1, UNEVALLED, 0,
542 doc: /* Like `quote', but preferred for objects which are functions.
543 In byte compilation, `function' causes its argument to be compiled.
544 `quote' cannot do that.
545 usage: (function ARG) */)
546 (Lisp_Object args)
548 Lisp_Object quoted = XCAR (args);
550 if (CONSP (XCDR (args)))
551 xsignal2 (Qwrong_number_of_arguments, Qfunction, Flength (args));
553 if (!NILP (Vinternal_interpreter_environment)
554 && CONSP (quoted)
555 && EQ (XCAR (quoted), Qlambda))
556 { /* This is a lambda expression within a lexical environment;
557 return an interpreted closure instead of a simple lambda. */
558 Lisp_Object cdr = XCDR (quoted);
559 Lisp_Object tmp = cdr;
560 if (CONSP (tmp)
561 && (tmp = XCDR (tmp), CONSP (tmp))
562 && (tmp = XCAR (tmp), CONSP (tmp))
563 && (EQ (QCdocumentation, XCAR (tmp))))
564 { /* Handle the special (:documentation <form>) to build the docstring
565 dynamically. */
566 Lisp_Object docstring = eval_sub (Fcar (XCDR (tmp)));
567 CHECK_STRING (docstring);
568 cdr = Fcons (XCAR (cdr), Fcons (docstring, XCDR (XCDR (cdr))));
570 return Fcons (Qclosure, Fcons (Vinternal_interpreter_environment,
571 cdr));
573 else
574 /* Simply quote the argument. */
575 return quoted;
579 DEFUN ("defvaralias", Fdefvaralias, Sdefvaralias, 2, 3, 0,
580 doc: /* Make NEW-ALIAS a variable alias for symbol BASE-VARIABLE.
581 Aliased variables always have the same value; setting one sets the other.
582 Third arg DOCSTRING, if non-nil, is documentation for NEW-ALIAS. If it is
583 omitted or nil, NEW-ALIAS gets the documentation string of BASE-VARIABLE,
584 or of the variable at the end of the chain of aliases, if BASE-VARIABLE is
585 itself an alias. If NEW-ALIAS is bound, and BASE-VARIABLE is not,
586 then the value of BASE-VARIABLE is set to that of NEW-ALIAS.
587 The return value is BASE-VARIABLE. */)
588 (Lisp_Object new_alias, Lisp_Object base_variable, Lisp_Object docstring)
590 struct Lisp_Symbol *sym;
592 CHECK_SYMBOL (new_alias);
593 CHECK_SYMBOL (base_variable);
595 sym = XSYMBOL (new_alias);
597 if (sym->constant)
598 /* Not sure why, but why not? */
599 error ("Cannot make a constant an alias");
601 switch (sym->redirect)
603 case SYMBOL_FORWARDED:
604 error ("Cannot make an internal variable an alias");
605 case SYMBOL_LOCALIZED:
606 error ("Don't know how to make a localized variable an alias");
607 case SYMBOL_PLAINVAL:
608 case SYMBOL_VARALIAS:
609 break;
610 default:
611 emacs_abort ();
614 /* http://lists.gnu.org/archive/html/emacs-devel/2008-04/msg00834.html
615 If n_a is bound, but b_v is not, set the value of b_v to n_a,
616 so that old-code that affects n_a before the aliasing is setup
617 still works. */
618 if (NILP (Fboundp (base_variable)))
619 set_internal (base_variable, find_symbol_value (new_alias), Qnil, 1);
622 union specbinding *p;
624 for (p = specpdl_ptr; p > specpdl; )
625 if ((--p)->kind >= SPECPDL_LET
626 && (EQ (new_alias, specpdl_symbol (p))))
627 error ("Don't know how to make a let-bound variable an alias");
630 sym->declared_special = 1;
631 XSYMBOL (base_variable)->declared_special = 1;
632 sym->redirect = SYMBOL_VARALIAS;
633 SET_SYMBOL_ALIAS (sym, XSYMBOL (base_variable));
634 sym->constant = SYMBOL_CONSTANT_P (base_variable);
635 LOADHIST_ATTACH (new_alias);
636 /* Even if docstring is nil: remove old docstring. */
637 Fput (new_alias, Qvariable_documentation, docstring);
639 return base_variable;
642 static union specbinding *
643 default_toplevel_binding (Lisp_Object symbol)
645 union specbinding *binding = NULL;
646 union specbinding *pdl = specpdl_ptr;
647 while (pdl > specpdl)
649 switch ((--pdl)->kind)
651 case SPECPDL_LET_DEFAULT:
652 case SPECPDL_LET:
653 if (EQ (specpdl_symbol (pdl), symbol))
654 binding = pdl;
655 break;
657 case SPECPDL_UNWIND:
658 case SPECPDL_UNWIND_PTR:
659 case SPECPDL_UNWIND_INT:
660 case SPECPDL_UNWIND_VOID:
661 case SPECPDL_BACKTRACE:
662 case SPECPDL_LET_LOCAL:
663 break;
665 default:
666 emacs_abort ();
669 return binding;
672 DEFUN ("default-toplevel-value", Fdefault_toplevel_value, Sdefault_toplevel_value, 1, 1, 0,
673 doc: /* Return SYMBOL's toplevel default value.
674 "Toplevel" means outside of any let binding. */)
675 (Lisp_Object symbol)
677 union specbinding *binding = default_toplevel_binding (symbol);
678 Lisp_Object value
679 = binding ? specpdl_old_value (binding) : Fdefault_value (symbol);
680 if (!EQ (value, Qunbound))
681 return value;
682 xsignal1 (Qvoid_variable, symbol);
685 DEFUN ("set-default-toplevel-value", Fset_default_toplevel_value,
686 Sset_default_toplevel_value, 2, 2, 0,
687 doc: /* Set SYMBOL's toplevel default value to VALUE.
688 "Toplevel" means outside of any let binding. */)
689 (Lisp_Object symbol, Lisp_Object value)
691 union specbinding *binding = default_toplevel_binding (symbol);
692 if (binding)
693 set_specpdl_old_value (binding, value);
694 else
695 Fset_default (symbol, value);
696 return Qnil;
699 DEFUN ("defvar", Fdefvar, Sdefvar, 1, UNEVALLED, 0,
700 doc: /* Define SYMBOL as a variable, and return SYMBOL.
701 You are not required to define a variable in order to use it, but
702 defining it lets you supply an initial value and documentation, which
703 can be referred to by the Emacs help facilities and other programming
704 tools. The `defvar' form also declares the variable as \"special\",
705 so that it is always dynamically bound even if `lexical-binding' is t.
707 The optional argument INITVALUE is evaluated, and used to set SYMBOL,
708 only if SYMBOL's value is void. If SYMBOL is buffer-local, its
709 default value is what is set; buffer-local values are not affected.
710 If INITVALUE is missing, SYMBOL's value is not set.
712 If SYMBOL has a local binding, then this form affects the local
713 binding. This is usually not what you want. Thus, if you need to
714 load a file defining variables, with this form or with `defconst' or
715 `defcustom', you should always load that file _outside_ any bindings
716 for these variables. (`defconst' and `defcustom' behave similarly in
717 this respect.)
719 The optional argument DOCSTRING is a documentation string for the
720 variable.
722 To define a user option, use `defcustom' instead of `defvar'.
723 usage: (defvar SYMBOL &optional INITVALUE DOCSTRING) */)
724 (Lisp_Object args)
726 Lisp_Object sym, tem, tail;
728 sym = XCAR (args);
729 tail = XCDR (args);
731 if (CONSP (tail))
733 if (CONSP (XCDR (tail)) && CONSP (XCDR (XCDR (tail))))
734 error ("Too many arguments");
736 tem = Fdefault_boundp (sym);
738 /* Do it before evaluating the initial value, for self-references. */
739 XSYMBOL (sym)->declared_special = 1;
741 if (NILP (tem))
742 Fset_default (sym, eval_sub (XCAR (tail)));
743 else
744 { /* Check if there is really a global binding rather than just a let
745 binding that shadows the global unboundness of the var. */
746 union specbinding *binding = default_toplevel_binding (sym);
747 if (binding && EQ (specpdl_old_value (binding), Qunbound))
749 set_specpdl_old_value (binding, eval_sub (XCAR (tail)));
752 tail = XCDR (tail);
753 tem = Fcar (tail);
754 if (!NILP (tem))
756 if (!NILP (Vpurify_flag))
757 tem = Fpurecopy (tem);
758 Fput (sym, Qvariable_documentation, tem);
760 LOADHIST_ATTACH (sym);
762 else if (!NILP (Vinternal_interpreter_environment)
763 && !XSYMBOL (sym)->declared_special)
764 /* A simple (defvar foo) with lexical scoping does "nothing" except
765 declare that var to be dynamically scoped *locally* (i.e. within
766 the current file or let-block). */
767 Vinternal_interpreter_environment
768 = Fcons (sym, Vinternal_interpreter_environment);
769 else
771 /* Simple (defvar <var>) should not count as a definition at all.
772 It could get in the way of other definitions, and unloading this
773 package could try to make the variable unbound. */
776 return sym;
779 DEFUN ("defconst", Fdefconst, Sdefconst, 2, UNEVALLED, 0,
780 doc: /* Define SYMBOL as a constant variable.
781 This declares that neither programs nor users should ever change the
782 value. This constancy is not actually enforced by Emacs Lisp, but
783 SYMBOL is marked as a special variable so that it is never lexically
784 bound.
786 The `defconst' form always sets the value of SYMBOL to the result of
787 evalling INITVALUE. If SYMBOL is buffer-local, its default value is
788 what is set; buffer-local values are not affected. If SYMBOL has a
789 local binding, then this form sets the local binding's value.
790 However, you should normally not make local bindings for variables
791 defined with this form.
793 The optional DOCSTRING specifies the variable's documentation string.
794 usage: (defconst SYMBOL INITVALUE [DOCSTRING]) */)
795 (Lisp_Object args)
797 Lisp_Object sym, tem;
799 sym = XCAR (args);
800 if (CONSP (Fcdr (XCDR (XCDR (args)))))
801 error ("Too many arguments");
803 tem = eval_sub (Fcar (XCDR (args)));
804 if (!NILP (Vpurify_flag))
805 tem = Fpurecopy (tem);
806 Fset_default (sym, tem);
807 XSYMBOL (sym)->declared_special = 1;
808 tem = Fcar (XCDR (XCDR (args)));
809 if (!NILP (tem))
811 if (!NILP (Vpurify_flag))
812 tem = Fpurecopy (tem);
813 Fput (sym, Qvariable_documentation, tem);
815 Fput (sym, Qrisky_local_variable, Qt);
816 LOADHIST_ATTACH (sym);
817 return sym;
820 /* Make SYMBOL lexically scoped. */
821 DEFUN ("internal-make-var-non-special", Fmake_var_non_special,
822 Smake_var_non_special, 1, 1, 0,
823 doc: /* Internal function. */)
824 (Lisp_Object symbol)
826 CHECK_SYMBOL (symbol);
827 XSYMBOL (symbol)->declared_special = 0;
828 return Qnil;
832 DEFUN ("let*", FletX, SletX, 1, UNEVALLED, 0,
833 doc: /* Bind variables according to VARLIST then eval BODY.
834 The value of the last form in BODY is returned.
835 Each element of VARLIST is a symbol (which is bound to nil)
836 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
837 Each VALUEFORM can refer to the symbols already bound by this VARLIST.
838 usage: (let* VARLIST BODY...) */)
839 (Lisp_Object args)
841 Lisp_Object varlist, var, val, elt, lexenv;
842 ptrdiff_t count = SPECPDL_INDEX ();
844 lexenv = Vinternal_interpreter_environment;
846 varlist = XCAR (args);
847 while (CONSP (varlist))
849 QUIT;
851 elt = XCAR (varlist);
852 if (SYMBOLP (elt))
854 var = elt;
855 val = Qnil;
857 else if (! NILP (Fcdr (Fcdr (elt))))
858 signal_error ("`let' bindings can have only one value-form", elt);
859 else
861 var = Fcar (elt);
862 val = eval_sub (Fcar (Fcdr (elt)));
865 if (!NILP (lexenv) && SYMBOLP (var)
866 && !XSYMBOL (var)->declared_special
867 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
868 /* Lexically bind VAR by adding it to the interpreter's binding
869 alist. */
871 Lisp_Object newenv
872 = Fcons (Fcons (var, val), Vinternal_interpreter_environment);
873 if (EQ (Vinternal_interpreter_environment, lexenv))
874 /* Save the old lexical environment on the specpdl stack,
875 but only for the first lexical binding, since we'll never
876 need to revert to one of the intermediate ones. */
877 specbind (Qinternal_interpreter_environment, newenv);
878 else
879 Vinternal_interpreter_environment = newenv;
881 else
882 specbind (var, val);
884 varlist = XCDR (varlist);
887 val = Fprogn (XCDR (args));
888 return unbind_to (count, val);
891 DEFUN ("let", Flet, Slet, 1, UNEVALLED, 0,
892 doc: /* Bind variables according to VARLIST then eval BODY.
893 The value of the last form in BODY is returned.
894 Each element of VARLIST is a symbol (which is bound to nil)
895 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
896 All the VALUEFORMs are evalled before any symbols are bound.
897 usage: (let VARLIST BODY...) */)
898 (Lisp_Object args)
900 Lisp_Object *temps, tem, lexenv;
901 Lisp_Object elt, varlist;
902 ptrdiff_t count = SPECPDL_INDEX ();
903 ptrdiff_t argnum;
904 USE_SAFE_ALLOCA;
906 varlist = XCAR (args);
908 /* Make space to hold the values to give the bound variables. */
909 elt = Flength (varlist);
910 SAFE_ALLOCA_LISP (temps, XFASTINT (elt));
912 /* Compute the values and store them in `temps'. */
914 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
916 QUIT;
917 elt = XCAR (varlist);
918 if (SYMBOLP (elt))
919 temps [argnum++] = Qnil;
920 else if (! NILP (Fcdr (Fcdr (elt))))
921 signal_error ("`let' bindings can have only one value-form", elt);
922 else
923 temps [argnum++] = eval_sub (Fcar (Fcdr (elt)));
926 lexenv = Vinternal_interpreter_environment;
928 varlist = XCAR (args);
929 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
931 Lisp_Object var;
933 elt = XCAR (varlist);
934 var = SYMBOLP (elt) ? elt : Fcar (elt);
935 tem = temps[argnum++];
937 if (!NILP (lexenv) && SYMBOLP (var)
938 && !XSYMBOL (var)->declared_special
939 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
940 /* Lexically bind VAR by adding it to the lexenv alist. */
941 lexenv = Fcons (Fcons (var, tem), lexenv);
942 else
943 /* Dynamically bind VAR. */
944 specbind (var, tem);
947 if (!EQ (lexenv, Vinternal_interpreter_environment))
948 /* Instantiate a new lexical environment. */
949 specbind (Qinternal_interpreter_environment, lexenv);
951 elt = Fprogn (XCDR (args));
952 SAFE_FREE ();
953 return unbind_to (count, elt);
956 DEFUN ("while", Fwhile, Swhile, 1, UNEVALLED, 0,
957 doc: /* If TEST yields non-nil, eval BODY... and repeat.
958 The order of execution is thus TEST, BODY, TEST, BODY and so on
959 until TEST returns nil.
960 usage: (while TEST BODY...) */)
961 (Lisp_Object args)
963 Lisp_Object test, body;
965 test = XCAR (args);
966 body = XCDR (args);
967 while (!NILP (eval_sub (test)))
969 QUIT;
970 Fprogn (body);
973 return Qnil;
976 DEFUN ("macroexpand", Fmacroexpand, Smacroexpand, 1, 2, 0,
977 doc: /* Return result of expanding macros at top level of FORM.
978 If FORM is not a macro call, it is returned unchanged.
979 Otherwise, the macro is expanded and the expansion is considered
980 in place of FORM. When a non-macro-call results, it is returned.
982 The second optional arg ENVIRONMENT specifies an environment of macro
983 definitions to shadow the loaded ones for use in file byte-compilation. */)
984 (Lisp_Object form, Lisp_Object environment)
986 /* With cleanups from Hallvard Furuseth. */
987 register Lisp_Object expander, sym, def, tem;
989 while (1)
991 /* Come back here each time we expand a macro call,
992 in case it expands into another macro call. */
993 if (!CONSP (form))
994 break;
995 /* Set SYM, give DEF and TEM right values in case SYM is not a symbol. */
996 def = sym = XCAR (form);
997 tem = Qnil;
998 /* Trace symbols aliases to other symbols
999 until we get a symbol that is not an alias. */
1000 while (SYMBOLP (def))
1002 QUIT;
1003 sym = def;
1004 tem = Fassq (sym, environment);
1005 if (NILP (tem))
1007 def = XSYMBOL (sym)->function;
1008 if (!NILP (def))
1009 continue;
1011 break;
1013 /* Right now TEM is the result from SYM in ENVIRONMENT,
1014 and if TEM is nil then DEF is SYM's function definition. */
1015 if (NILP (tem))
1017 /* SYM is not mentioned in ENVIRONMENT.
1018 Look at its function definition. */
1019 def = Fautoload_do_load (def, sym, Qmacro);
1020 if (!CONSP (def))
1021 /* Not defined or definition not suitable. */
1022 break;
1023 if (!EQ (XCAR (def), Qmacro))
1024 break;
1025 else expander = XCDR (def);
1027 else
1029 expander = XCDR (tem);
1030 if (NILP (expander))
1031 break;
1034 Lisp_Object newform = apply1 (expander, XCDR (form));
1035 if (EQ (form, newform))
1036 break;
1037 else
1038 form = newform;
1041 return form;
1044 DEFUN ("catch", Fcatch, Scatch, 1, UNEVALLED, 0,
1045 doc: /* Eval BODY allowing nonlocal exits using `throw'.
1046 TAG is evalled to get the tag to use; it must not be nil.
1048 Then the BODY is executed.
1049 Within BODY, a call to `throw' with the same TAG exits BODY and this `catch'.
1050 If no throw happens, `catch' returns the value of the last BODY form.
1051 If a throw happens, it specifies the value to return from `catch'.
1052 usage: (catch TAG BODY...) */)
1053 (Lisp_Object args)
1055 Lisp_Object tag = eval_sub (XCAR (args));
1056 return internal_catch (tag, Fprogn, XCDR (args));
1059 /* Assert that E is true, as a comment only. Use this instead of
1060 eassert (E) when E contains variables that might be clobbered by a
1061 longjmp. */
1063 #define clobbered_eassert(E) ((void) 0)
1065 /* Set up a catch, then call C function FUNC on argument ARG.
1066 FUNC should return a Lisp_Object.
1067 This is how catches are done from within C code. */
1069 Lisp_Object
1070 internal_catch (Lisp_Object tag,
1071 Lisp_Object (*func) (Lisp_Object), Lisp_Object arg)
1073 /* This structure is made part of the chain `catchlist'. */
1074 struct handler *c = push_handler (tag, CATCHER);
1076 /* Call FUNC. */
1077 if (! sys_setjmp (c->jmp))
1079 Lisp_Object val = func (arg);
1080 clobbered_eassert (handlerlist == c);
1081 handlerlist = handlerlist->next;
1082 return val;
1084 else
1085 { /* Throw works by a longjmp that comes right here. */
1086 Lisp_Object val = handlerlist->val;
1087 clobbered_eassert (handlerlist == c);
1088 handlerlist = handlerlist->next;
1089 return val;
1093 /* Unwind the specbind, catch, and handler stacks back to CATCH, and
1094 jump to that CATCH, returning VALUE as the value of that catch.
1096 This is the guts of Fthrow and Fsignal; they differ only in the way
1097 they choose the catch tag to throw to. A catch tag for a
1098 condition-case form has a TAG of Qnil.
1100 Before each catch is discarded, unbind all special bindings and
1101 execute all unwind-protect clauses made above that catch. Unwind
1102 the handler stack as we go, so that the proper handlers are in
1103 effect for each unwind-protect clause we run. At the end, restore
1104 some static info saved in CATCH, and longjmp to the location
1105 specified there.
1107 This is used for correct unwinding in Fthrow and Fsignal. */
1109 static _Noreturn void
1110 unwind_to_catch (struct handler *catch, Lisp_Object value)
1112 bool last_time;
1114 eassert (catch->next);
1116 /* Save the value in the tag. */
1117 catch->val = value;
1119 /* Restore certain special C variables. */
1120 set_poll_suppress_count (catch->poll_suppress_count);
1121 unblock_input_to (catch->interrupt_input_blocked);
1122 immediate_quit = 0;
1126 /* Unwind the specpdl stack, and then restore the proper set of
1127 handlers. */
1128 unbind_to (handlerlist->pdlcount, Qnil);
1129 last_time = handlerlist == catch;
1130 if (! last_time)
1131 handlerlist = handlerlist->next;
1133 while (! last_time);
1135 eassert (handlerlist == catch);
1137 lisp_eval_depth = catch->lisp_eval_depth;
1139 sys_longjmp (catch->jmp, 1);
1142 DEFUN ("throw", Fthrow, Sthrow, 2, 2, 0,
1143 doc: /* Throw to the catch for TAG and return VALUE from it.
1144 Both TAG and VALUE are evalled. */
1145 attributes: noreturn)
1146 (register Lisp_Object tag, Lisp_Object value)
1148 struct handler *c;
1150 if (!NILP (tag))
1151 for (c = handlerlist; c; c = c->next)
1153 if (c->type == CATCHER_ALL)
1154 unwind_to_catch (c, Fcons (tag, value));
1155 if (c->type == CATCHER && EQ (c->tag_or_ch, tag))
1156 unwind_to_catch (c, value);
1158 xsignal2 (Qno_catch, tag, value);
1162 DEFUN ("unwind-protect", Funwind_protect, Sunwind_protect, 1, UNEVALLED, 0,
1163 doc: /* Do BODYFORM, protecting with UNWINDFORMS.
1164 If BODYFORM completes normally, its value is returned
1165 after executing the UNWINDFORMS.
1166 If BODYFORM exits nonlocally, the UNWINDFORMS are executed anyway.
1167 usage: (unwind-protect BODYFORM UNWINDFORMS...) */)
1168 (Lisp_Object args)
1170 Lisp_Object val;
1171 ptrdiff_t count = SPECPDL_INDEX ();
1173 record_unwind_protect (unwind_body, XCDR (args));
1174 val = eval_sub (XCAR (args));
1175 return unbind_to (count, val);
1178 DEFUN ("condition-case", Fcondition_case, Scondition_case, 2, UNEVALLED, 0,
1179 doc: /* Regain control when an error is signaled.
1180 Executes BODYFORM and returns its value if no error happens.
1181 Each element of HANDLERS looks like (CONDITION-NAME BODY...)
1182 where the BODY is made of Lisp expressions.
1184 A handler is applicable to an error
1185 if CONDITION-NAME is one of the error's condition names.
1186 If an error happens, the first applicable handler is run.
1188 The car of a handler may be a list of condition names instead of a
1189 single condition name; then it handles all of them. If the special
1190 condition name `debug' is present in this list, it allows another
1191 condition in the list to run the debugger if `debug-on-error' and the
1192 other usual mechanisms says it should (otherwise, `condition-case'
1193 suppresses the debugger).
1195 When a handler handles an error, control returns to the `condition-case'
1196 and it executes the handler's BODY...
1197 with VAR bound to (ERROR-SYMBOL . SIGNAL-DATA) from the error.
1198 \(If VAR is nil, the handler can't access that information.)
1199 Then the value of the last BODY form is returned from the `condition-case'
1200 expression.
1202 See also the function `signal' for more info.
1203 usage: (condition-case VAR BODYFORM &rest HANDLERS) */)
1204 (Lisp_Object args)
1206 Lisp_Object var = XCAR (args);
1207 Lisp_Object bodyform = XCAR (XCDR (args));
1208 Lisp_Object handlers = XCDR (XCDR (args));
1210 return internal_lisp_condition_case (var, bodyform, handlers);
1213 /* Like Fcondition_case, but the args are separate
1214 rather than passed in a list. Used by Fbyte_code. */
1216 Lisp_Object
1217 internal_lisp_condition_case (volatile Lisp_Object var, Lisp_Object bodyform,
1218 Lisp_Object handlers)
1220 Lisp_Object val;
1221 struct handler *oldhandlerlist = handlerlist;
1222 int clausenb = 0;
1224 CHECK_SYMBOL (var);
1226 for (val = handlers; CONSP (val); val = XCDR (val))
1228 Lisp_Object tem = XCAR (val);
1229 clausenb++;
1230 if (! (NILP (tem)
1231 || (CONSP (tem)
1232 && (SYMBOLP (XCAR (tem))
1233 || CONSP (XCAR (tem))))))
1234 error ("Invalid condition handler: %s",
1235 SDATA (Fprin1_to_string (tem, Qt)));
1238 { /* The first clause is the one that should be checked first, so it should
1239 be added to handlerlist last. So we build in `clauses' a table that
1240 contains `handlers' but in reverse order. SAFE_ALLOCA won't work
1241 here due to the setjmp, so impose a MAX_ALLOCA limit. */
1242 if (MAX_ALLOCA / word_size < clausenb)
1243 memory_full (SIZE_MAX);
1244 Lisp_Object *clauses = alloca (clausenb * sizeof *clauses);
1245 Lisp_Object *volatile clauses_volatile = clauses;
1246 int i = clausenb;
1247 for (val = handlers; CONSP (val); val = XCDR (val))
1248 clauses[--i] = XCAR (val);
1249 for (i = 0; i < clausenb; i++)
1251 Lisp_Object clause = clauses[i];
1252 Lisp_Object condition = CONSP (clause) ? XCAR (clause) : Qnil;
1253 if (!CONSP (condition))
1254 condition = Fcons (condition, Qnil);
1255 struct handler *c = push_handler (condition, CONDITION_CASE);
1256 if (sys_setjmp (c->jmp))
1258 ptrdiff_t count = SPECPDL_INDEX ();
1259 Lisp_Object val = handlerlist->val;
1260 Lisp_Object *chosen_clause = clauses_volatile;
1261 for (c = handlerlist->next; c != oldhandlerlist; c = c->next)
1262 chosen_clause++;
1263 handlerlist = oldhandlerlist;
1264 if (!NILP (var))
1266 if (!NILP (Vinternal_interpreter_environment))
1267 specbind (Qinternal_interpreter_environment,
1268 Fcons (Fcons (var, val),
1269 Vinternal_interpreter_environment));
1270 else
1271 specbind (var, val);
1273 val = Fprogn (XCDR (*chosen_clause));
1274 /* Note that this just undoes the binding of var; whoever
1275 longjumped to us unwound the stack to c.pdlcount before
1276 throwing. */
1277 if (!NILP (var))
1278 unbind_to (count, Qnil);
1279 return val;
1284 val = eval_sub (bodyform);
1285 handlerlist = oldhandlerlist;
1286 return val;
1289 /* Call the function BFUN with no arguments, catching errors within it
1290 according to HANDLERS. If there is an error, call HFUN with
1291 one argument which is the data that describes the error:
1292 (SIGNALNAME . DATA)
1294 HANDLERS can be a list of conditions to catch.
1295 If HANDLERS is Qt, catch all errors.
1296 If HANDLERS is Qerror, catch all errors
1297 but allow the debugger to run if that is enabled. */
1299 Lisp_Object
1300 internal_condition_case (Lisp_Object (*bfun) (void), Lisp_Object handlers,
1301 Lisp_Object (*hfun) (Lisp_Object))
1303 struct handler *c = push_handler (handlers, CONDITION_CASE);
1304 if (sys_setjmp (c->jmp))
1306 Lisp_Object val = handlerlist->val;
1307 clobbered_eassert (handlerlist == c);
1308 handlerlist = handlerlist->next;
1309 return hfun (val);
1311 else
1313 Lisp_Object val = bfun ();
1314 clobbered_eassert (handlerlist == c);
1315 handlerlist = handlerlist->next;
1316 return val;
1320 /* Like internal_condition_case but call BFUN with ARG as its argument. */
1322 Lisp_Object
1323 internal_condition_case_1 (Lisp_Object (*bfun) (Lisp_Object), Lisp_Object arg,
1324 Lisp_Object handlers,
1325 Lisp_Object (*hfun) (Lisp_Object))
1327 struct handler *c = push_handler (handlers, CONDITION_CASE);
1328 if (sys_setjmp (c->jmp))
1330 Lisp_Object val = handlerlist->val;
1331 clobbered_eassert (handlerlist == c);
1332 handlerlist = handlerlist->next;
1333 return hfun (val);
1335 else
1337 Lisp_Object val = bfun (arg);
1338 clobbered_eassert (handlerlist == c);
1339 handlerlist = handlerlist->next;
1340 return val;
1344 /* Like internal_condition_case_1 but call BFUN with ARG1 and ARG2 as
1345 its arguments. */
1347 Lisp_Object
1348 internal_condition_case_2 (Lisp_Object (*bfun) (Lisp_Object, Lisp_Object),
1349 Lisp_Object arg1,
1350 Lisp_Object arg2,
1351 Lisp_Object handlers,
1352 Lisp_Object (*hfun) (Lisp_Object))
1354 struct handler *c = push_handler (handlers, CONDITION_CASE);
1355 if (sys_setjmp (c->jmp))
1357 Lisp_Object val = handlerlist->val;
1358 clobbered_eassert (handlerlist == c);
1359 handlerlist = handlerlist->next;
1360 return hfun (val);
1362 else
1364 Lisp_Object val = bfun (arg1, arg2);
1365 clobbered_eassert (handlerlist == c);
1366 handlerlist = handlerlist->next;
1367 return val;
1371 /* Like internal_condition_case but call BFUN with NARGS as first,
1372 and ARGS as second argument. */
1374 Lisp_Object
1375 internal_condition_case_n (Lisp_Object (*bfun) (ptrdiff_t, Lisp_Object *),
1376 ptrdiff_t nargs,
1377 Lisp_Object *args,
1378 Lisp_Object handlers,
1379 Lisp_Object (*hfun) (Lisp_Object err,
1380 ptrdiff_t nargs,
1381 Lisp_Object *args))
1383 struct handler *c = push_handler (handlers, CONDITION_CASE);
1384 if (sys_setjmp (c->jmp))
1386 Lisp_Object val = handlerlist->val;
1387 clobbered_eassert (handlerlist == c);
1388 handlerlist = handlerlist->next;
1389 return hfun (val, nargs, args);
1391 else
1393 Lisp_Object val = bfun (nargs, args);
1394 clobbered_eassert (handlerlist == c);
1395 handlerlist = handlerlist->next;
1396 return val;
1400 struct handler *
1401 push_handler (Lisp_Object tag_ch_val, enum handlertype handlertype)
1403 struct handler *c = push_handler_nosignal (tag_ch_val, handlertype);
1404 if (!c)
1405 memory_full (sizeof *c);
1406 return c;
1409 struct handler *
1410 push_handler_nosignal (Lisp_Object tag_ch_val, enum handlertype handlertype)
1412 struct handler *c = handlerlist->nextfree;
1413 if (!c)
1415 c = malloc (sizeof *c);
1416 if (!c)
1417 return c;
1418 if (profiler_memory_running)
1419 malloc_probe (sizeof *c);
1420 c->nextfree = NULL;
1421 handlerlist->nextfree = c;
1423 c->type = handlertype;
1424 c->tag_or_ch = tag_ch_val;
1425 c->val = Qnil;
1426 c->next = handlerlist;
1427 c->lisp_eval_depth = lisp_eval_depth;
1428 c->pdlcount = SPECPDL_INDEX ();
1429 c->poll_suppress_count = poll_suppress_count;
1430 c->interrupt_input_blocked = interrupt_input_blocked;
1431 handlerlist = c;
1432 return c;
1436 static Lisp_Object signal_or_quit (Lisp_Object, Lisp_Object, bool);
1437 static Lisp_Object find_handler_clause (Lisp_Object, Lisp_Object);
1438 static bool maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig,
1439 Lisp_Object data);
1441 void
1442 process_quit_flag (void)
1444 Lisp_Object flag = Vquit_flag;
1445 Vquit_flag = Qnil;
1446 if (EQ (flag, Qkill_emacs))
1447 Fkill_emacs (Qnil);
1448 if (EQ (Vthrow_on_input, flag))
1449 Fthrow (Vthrow_on_input, Qt);
1450 quit ();
1453 DEFUN ("signal", Fsignal, Ssignal, 2, 2, 0,
1454 doc: /* Signal an error. Args are ERROR-SYMBOL and associated DATA.
1455 This function does not return.
1457 An error symbol is a symbol with an `error-conditions' property
1458 that is a list of condition names.
1459 A handler for any of those names will get to handle this signal.
1460 The symbol `error' should normally be one of them.
1462 DATA should be a list. Its elements are printed as part of the error message.
1463 See Info anchor `(elisp)Definition of signal' for some details on how this
1464 error message is constructed.
1465 If the signal is handled, DATA is made available to the handler.
1466 See also the function `condition-case'. */
1467 attributes: noreturn)
1468 (Lisp_Object error_symbol, Lisp_Object data)
1470 signal_or_quit (error_symbol, data, false);
1471 eassume (false);
1474 /* Quit, in response to a keyboard quit request. */
1475 Lisp_Object
1476 quit (void)
1478 return signal_or_quit (Qquit, Qnil, true);
1481 /* Signal an error, or quit. ERROR_SYMBOL and DATA are as with Fsignal.
1482 If KEYBOARD_QUIT, this is a quit; ERROR_SYMBOL should be
1483 Qquit and DATA should be Qnil, and this function may return.
1484 Otherwise this function is like Fsignal and does not return. */
1486 static Lisp_Object
1487 signal_or_quit (Lisp_Object error_symbol, Lisp_Object data, bool keyboard_quit)
1489 /* When memory is full, ERROR-SYMBOL is nil,
1490 and DATA is (REAL-ERROR-SYMBOL . REAL-DATA).
1491 That is a special case--don't do this in other situations. */
1492 Lisp_Object conditions;
1493 Lisp_Object string;
1494 Lisp_Object real_error_symbol
1495 = (NILP (error_symbol) ? Fcar (data) : error_symbol);
1496 register Lisp_Object clause = Qnil;
1497 struct handler *h;
1499 immediate_quit = 0;
1500 abort_on_gc = 0;
1501 if (gc_in_progress || waiting_for_input)
1502 emacs_abort ();
1504 #if 0 /* rms: I don't know why this was here,
1505 but it is surely wrong for an error that is handled. */
1506 #ifdef HAVE_WINDOW_SYSTEM
1507 if (display_hourglass_p)
1508 cancel_hourglass ();
1509 #endif
1510 #endif
1512 /* This hook is used by edebug. */
1513 if (! NILP (Vsignal_hook_function)
1514 && ! NILP (error_symbol))
1516 /* Edebug takes care of restoring these variables when it exits. */
1517 if (lisp_eval_depth + 20 > max_lisp_eval_depth)
1518 max_lisp_eval_depth = lisp_eval_depth + 20;
1520 if (SPECPDL_INDEX () + 40 > max_specpdl_size)
1521 max_specpdl_size = SPECPDL_INDEX () + 40;
1523 call2 (Vsignal_hook_function, error_symbol, data);
1526 conditions = Fget (real_error_symbol, Qerror_conditions);
1528 /* Remember from where signal was called. Skip over the frame for
1529 `signal' itself. If a frame for `error' follows, skip that,
1530 too. Don't do this when ERROR_SYMBOL is nil, because that
1531 is a memory-full error. */
1532 Vsignaling_function = Qnil;
1533 if (!NILP (error_symbol))
1535 union specbinding *pdl = backtrace_next (backtrace_top ());
1536 if (backtrace_p (pdl) && EQ (backtrace_function (pdl), Qerror))
1537 pdl = backtrace_next (pdl);
1538 if (backtrace_p (pdl))
1539 Vsignaling_function = backtrace_function (pdl);
1542 for (h = handlerlist; h; h = h->next)
1544 if (h->type != CONDITION_CASE)
1545 continue;
1546 clause = find_handler_clause (h->tag_or_ch, conditions);
1547 if (!NILP (clause))
1548 break;
1551 if (/* Don't run the debugger for a memory-full error.
1552 (There is no room in memory to do that!) */
1553 !NILP (error_symbol)
1554 && (!NILP (Vdebug_on_signal)
1555 /* If no handler is present now, try to run the debugger. */
1556 || NILP (clause)
1557 /* A `debug' symbol in the handler list disables the normal
1558 suppression of the debugger. */
1559 || (CONSP (clause) && !NILP (Fmemq (Qdebug, clause)))
1560 /* Special handler that means "print a message and run debugger
1561 if requested". */
1562 || EQ (h->tag_or_ch, Qerror)))
1564 bool debugger_called
1565 = maybe_call_debugger (conditions, error_symbol, data);
1566 /* We can't return values to code which signaled an error, but we
1567 can continue code which has signaled a quit. */
1568 if (keyboard_quit && debugger_called && EQ (real_error_symbol, Qquit))
1569 return Qnil;
1572 if (!NILP (clause))
1574 Lisp_Object unwind_data
1575 = (NILP (error_symbol) ? data : Fcons (error_symbol, data));
1577 unwind_to_catch (h, unwind_data);
1579 else
1581 if (handlerlist != &handlerlist_sentinel)
1582 /* FIXME: This will come right back here if there's no `top-level'
1583 catcher. A better solution would be to abort here, and instead
1584 add a catch-all condition handler so we never come here. */
1585 Fthrow (Qtop_level, Qt);
1588 if (! NILP (error_symbol))
1589 data = Fcons (error_symbol, data);
1591 string = Ferror_message_string (data);
1592 fatal ("%s", SDATA (string));
1595 /* Like xsignal, but takes 0, 1, 2, or 3 args instead of a list. */
1597 void
1598 xsignal0 (Lisp_Object error_symbol)
1600 xsignal (error_symbol, Qnil);
1603 void
1604 xsignal1 (Lisp_Object error_symbol, Lisp_Object arg)
1606 xsignal (error_symbol, list1 (arg));
1609 void
1610 xsignal2 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2)
1612 xsignal (error_symbol, list2 (arg1, arg2));
1615 void
1616 xsignal3 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
1618 xsignal (error_symbol, list3 (arg1, arg2, arg3));
1621 /* Signal `error' with message S, and additional arg ARG.
1622 If ARG is not a genuine list, make it a one-element list. */
1624 void
1625 signal_error (const char *s, Lisp_Object arg)
1627 Lisp_Object tortoise, hare;
1629 hare = tortoise = arg;
1630 while (CONSP (hare))
1632 hare = XCDR (hare);
1633 if (!CONSP (hare))
1634 break;
1636 hare = XCDR (hare);
1637 tortoise = XCDR (tortoise);
1639 if (EQ (hare, tortoise))
1640 break;
1643 if (!NILP (hare))
1644 arg = list1 (arg);
1646 xsignal (Qerror, Fcons (build_string (s), arg));
1650 /* Return true if LIST is a non-nil atom or
1651 a list containing one of CONDITIONS. */
1653 static bool
1654 wants_debugger (Lisp_Object list, Lisp_Object conditions)
1656 if (NILP (list))
1657 return 0;
1658 if (! CONSP (list))
1659 return 1;
1661 while (CONSP (conditions))
1663 Lisp_Object this, tail;
1664 this = XCAR (conditions);
1665 for (tail = list; CONSP (tail); tail = XCDR (tail))
1666 if (EQ (XCAR (tail), this))
1667 return 1;
1668 conditions = XCDR (conditions);
1670 return 0;
1673 /* Return true if an error with condition-symbols CONDITIONS,
1674 and described by SIGNAL-DATA, should skip the debugger
1675 according to debugger-ignored-errors. */
1677 static bool
1678 skip_debugger (Lisp_Object conditions, Lisp_Object data)
1680 Lisp_Object tail;
1681 bool first_string = 1;
1682 Lisp_Object error_message;
1684 error_message = Qnil;
1685 for (tail = Vdebug_ignored_errors; CONSP (tail); tail = XCDR (tail))
1687 if (STRINGP (XCAR (tail)))
1689 if (first_string)
1691 error_message = Ferror_message_string (data);
1692 first_string = 0;
1695 if (fast_string_match (XCAR (tail), error_message) >= 0)
1696 return 1;
1698 else
1700 Lisp_Object contail;
1702 for (contail = conditions; CONSP (contail); contail = XCDR (contail))
1703 if (EQ (XCAR (tail), XCAR (contail)))
1704 return 1;
1708 return 0;
1711 /* Call the debugger if calling it is currently enabled for CONDITIONS.
1712 SIG and DATA describe the signal. There are two ways to pass them:
1713 = SIG is the error symbol, and DATA is the rest of the data.
1714 = SIG is nil, and DATA is (SYMBOL . REST-OF-DATA).
1715 This is for memory-full errors only. */
1716 static bool
1717 maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig, Lisp_Object data)
1719 Lisp_Object combined_data;
1721 combined_data = Fcons (sig, data);
1723 if (
1724 /* Don't try to run the debugger with interrupts blocked.
1725 The editing loop would return anyway. */
1726 ! input_blocked_p ()
1727 && NILP (Vinhibit_debugger)
1728 /* Does user want to enter debugger for this kind of error? */
1729 && (EQ (sig, Qquit)
1730 ? debug_on_quit
1731 : wants_debugger (Vdebug_on_error, conditions))
1732 && ! skip_debugger (conditions, combined_data)
1733 /* RMS: What's this for? */
1734 && when_entered_debugger < num_nonmacro_input_events)
1736 call_debugger (list2 (Qerror, combined_data));
1737 return 1;
1740 return 0;
1743 static Lisp_Object
1744 find_handler_clause (Lisp_Object handlers, Lisp_Object conditions)
1746 register Lisp_Object h;
1748 /* t is used by handlers for all conditions, set up by C code. */
1749 if (EQ (handlers, Qt))
1750 return Qt;
1752 /* error is used similarly, but means print an error message
1753 and run the debugger if that is enabled. */
1754 if (EQ (handlers, Qerror))
1755 return Qt;
1757 for (h = handlers; CONSP (h); h = XCDR (h))
1759 Lisp_Object handler = XCAR (h);
1760 if (!NILP (Fmemq (handler, conditions)))
1761 return handlers;
1764 return Qnil;
1768 /* Format and return a string; called like vprintf. */
1769 Lisp_Object
1770 vformat_string (const char *m, va_list ap)
1772 char buf[4000];
1773 ptrdiff_t size = sizeof buf;
1774 ptrdiff_t size_max = STRING_BYTES_BOUND + 1;
1775 char *buffer = buf;
1776 ptrdiff_t used;
1777 Lisp_Object string;
1779 used = evxprintf (&buffer, &size, buf, size_max, m, ap);
1780 string = make_string (buffer, used);
1781 if (buffer != buf)
1782 xfree (buffer);
1784 return string;
1787 /* Dump an error message; called like vprintf. */
1788 void
1789 verror (const char *m, va_list ap)
1791 xsignal1 (Qerror, vformat_string (m, ap));
1795 /* Dump an error message; called like printf. */
1797 /* VARARGS 1 */
1798 void
1799 error (const char *m, ...)
1801 va_list ap;
1802 va_start (ap, m);
1803 verror (m, ap);
1806 DEFUN ("commandp", Fcommandp, Scommandp, 1, 2, 0,
1807 doc: /* Non-nil if FUNCTION makes provisions for interactive calling.
1808 This means it contains a description for how to read arguments to give it.
1809 The value is nil for an invalid function or a symbol with no function
1810 definition.
1812 Interactively callable functions include strings and vectors (treated
1813 as keyboard macros), lambda-expressions that contain a top-level call
1814 to `interactive', autoload definitions made by `autoload' with non-nil
1815 fourth argument, and some of the built-in functions of Lisp.
1817 Also, a symbol satisfies `commandp' if its function definition does so.
1819 If the optional argument FOR-CALL-INTERACTIVELY is non-nil,
1820 then strings and vectors are not accepted. */)
1821 (Lisp_Object function, Lisp_Object for_call_interactively)
1823 register Lisp_Object fun;
1824 register Lisp_Object funcar;
1825 Lisp_Object if_prop = Qnil;
1827 fun = function;
1829 fun = indirect_function (fun); /* Check cycles. */
1830 if (NILP (fun))
1831 return Qnil;
1833 /* Check an `interactive-form' property if present, analogous to the
1834 function-documentation property. */
1835 fun = function;
1836 while (SYMBOLP (fun))
1838 Lisp_Object tmp = Fget (fun, Qinteractive_form);
1839 if (!NILP (tmp))
1840 if_prop = Qt;
1841 fun = Fsymbol_function (fun);
1844 /* Emacs primitives are interactive if their DEFUN specifies an
1845 interactive spec. */
1846 if (SUBRP (fun))
1847 return XSUBR (fun)->intspec ? Qt : if_prop;
1849 /* Bytecode objects are interactive if they are long enough to
1850 have an element whose index is COMPILED_INTERACTIVE, which is
1851 where the interactive spec is stored. */
1852 else if (COMPILEDP (fun))
1853 return ((ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK) > COMPILED_INTERACTIVE
1854 ? Qt : if_prop);
1856 /* Strings and vectors are keyboard macros. */
1857 if (STRINGP (fun) || VECTORP (fun))
1858 return (NILP (for_call_interactively) ? Qt : Qnil);
1860 /* Lists may represent commands. */
1861 if (!CONSP (fun))
1862 return Qnil;
1863 funcar = XCAR (fun);
1864 if (EQ (funcar, Qclosure))
1865 return (!NILP (Fassq (Qinteractive, Fcdr (Fcdr (XCDR (fun)))))
1866 ? Qt : if_prop);
1867 else if (EQ (funcar, Qlambda))
1868 return !NILP (Fassq (Qinteractive, Fcdr (XCDR (fun)))) ? Qt : if_prop;
1869 else if (EQ (funcar, Qautoload))
1870 return !NILP (Fcar (Fcdr (Fcdr (XCDR (fun))))) ? Qt : if_prop;
1871 else
1872 return Qnil;
1875 DEFUN ("autoload", Fautoload, Sautoload, 2, 5, 0,
1876 doc: /* Define FUNCTION to autoload from FILE.
1877 FUNCTION is a symbol; FILE is a file name string to pass to `load'.
1878 Third arg DOCSTRING is documentation for the function.
1879 Fourth arg INTERACTIVE if non-nil says function can be called interactively.
1880 Fifth arg TYPE indicates the type of the object:
1881 nil or omitted says FUNCTION is a function,
1882 `keymap' says FUNCTION is really a keymap, and
1883 `macro' or t says FUNCTION is really a macro.
1884 Third through fifth args give info about the real definition.
1885 They default to nil.
1886 If FUNCTION is already defined other than as an autoload,
1887 this does nothing and returns nil. */)
1888 (Lisp_Object function, Lisp_Object file, Lisp_Object docstring, Lisp_Object interactive, Lisp_Object type)
1890 CHECK_SYMBOL (function);
1891 CHECK_STRING (file);
1893 /* If function is defined and not as an autoload, don't override. */
1894 if (!NILP (XSYMBOL (function)->function)
1895 && !AUTOLOADP (XSYMBOL (function)->function))
1896 return Qnil;
1898 if (!NILP (Vpurify_flag) && EQ (docstring, make_number (0)))
1899 /* `read1' in lread.c has found the docstring starting with "\
1900 and assumed the docstring will be provided by Snarf-documentation, so it
1901 passed us 0 instead. But that leads to accidental sharing in purecopy's
1902 hash-consing, so we use a (hopefully) unique integer instead. */
1903 docstring = make_number (XHASH (function));
1904 return Fdefalias (function,
1905 list5 (Qautoload, file, docstring, interactive, type),
1906 Qnil);
1909 void
1910 un_autoload (Lisp_Object oldqueue)
1912 Lisp_Object queue, first, second;
1914 /* Queue to unwind is current value of Vautoload_queue.
1915 oldqueue is the shadowed value to leave in Vautoload_queue. */
1916 queue = Vautoload_queue;
1917 Vautoload_queue = oldqueue;
1918 while (CONSP (queue))
1920 first = XCAR (queue);
1921 second = Fcdr (first);
1922 first = Fcar (first);
1923 if (EQ (first, make_number (0)))
1924 Vfeatures = second;
1925 else
1926 Ffset (first, second);
1927 queue = XCDR (queue);
1931 /* Load an autoloaded function.
1932 FUNNAME is the symbol which is the function's name.
1933 FUNDEF is the autoload definition (a list). */
1935 DEFUN ("autoload-do-load", Fautoload_do_load, Sautoload_do_load, 1, 3, 0,
1936 doc: /* Load FUNDEF which should be an autoload.
1937 If non-nil, FUNNAME should be the symbol whose function value is FUNDEF,
1938 in which case the function returns the new autoloaded function value.
1939 If equal to `macro', MACRO-ONLY specifies that FUNDEF should only be loaded if
1940 it defines a macro. */)
1941 (Lisp_Object fundef, Lisp_Object funname, Lisp_Object macro_only)
1943 ptrdiff_t count = SPECPDL_INDEX ();
1945 if (!CONSP (fundef) || !EQ (Qautoload, XCAR (fundef)))
1946 return fundef;
1948 if (EQ (macro_only, Qmacro))
1950 Lisp_Object kind = Fnth (make_number (4), fundef);
1951 if (! (EQ (kind, Qt) || EQ (kind, Qmacro)))
1952 return fundef;
1955 /* This is to make sure that loadup.el gives a clear picture
1956 of what files are preloaded and when. */
1957 if (! NILP (Vpurify_flag))
1958 error ("Attempt to autoload %s while preparing to dump",
1959 SDATA (SYMBOL_NAME (funname)));
1961 CHECK_SYMBOL (funname);
1963 /* Preserve the match data. */
1964 record_unwind_save_match_data ();
1966 /* If autoloading gets an error (which includes the error of failing
1967 to define the function being called), we use Vautoload_queue
1968 to undo function definitions and `provide' calls made by
1969 the function. We do this in the specific case of autoloading
1970 because autoloading is not an explicit request "load this file",
1971 but rather a request to "call this function".
1973 The value saved here is to be restored into Vautoload_queue. */
1974 record_unwind_protect (un_autoload, Vautoload_queue);
1975 Vautoload_queue = Qt;
1976 /* If `macro_only', assume this autoload to be a "best-effort",
1977 so don't signal an error if autoloading fails. */
1978 Fload (Fcar (Fcdr (fundef)), macro_only, Qt, Qnil, Qt);
1980 /* Once loading finishes, don't undo it. */
1981 Vautoload_queue = Qt;
1982 unbind_to (count, Qnil);
1984 if (NILP (funname))
1985 return Qnil;
1986 else
1988 Lisp_Object fun = Findirect_function (funname, Qnil);
1990 if (!NILP (Fequal (fun, fundef)))
1991 error ("Autoloading failed to define function %s",
1992 SDATA (SYMBOL_NAME (funname)));
1993 else
1994 return fun;
1999 DEFUN ("eval", Feval, Seval, 1, 2, 0,
2000 doc: /* Evaluate FORM and return its value.
2001 If LEXICAL is t, evaluate using lexical scoping.
2002 LEXICAL can also be an actual lexical environment, in the form of an
2003 alist mapping symbols to their value. */)
2004 (Lisp_Object form, Lisp_Object lexical)
2006 ptrdiff_t count = SPECPDL_INDEX ();
2007 specbind (Qinternal_interpreter_environment,
2008 CONSP (lexical) || NILP (lexical) ? lexical : list1 (Qt));
2009 return unbind_to (count, eval_sub (form));
2012 /* Grow the specpdl stack by one entry.
2013 The caller should have already initialized the entry.
2014 Signal an error on stack overflow.
2016 Make sure that there is always one unused entry past the top of the
2017 stack, so that the just-initialized entry is safely unwound if
2018 memory exhausted and an error is signaled here. Also, allocate a
2019 never-used entry just before the bottom of the stack; sometimes its
2020 address is taken. */
2022 static void
2023 grow_specpdl (void)
2025 specpdl_ptr++;
2027 if (specpdl_ptr == specpdl + specpdl_size)
2029 ptrdiff_t count = SPECPDL_INDEX ();
2030 ptrdiff_t max_size = min (max_specpdl_size, PTRDIFF_MAX - 1000);
2031 union specbinding *pdlvec = specpdl - 1;
2032 ptrdiff_t pdlvecsize = specpdl_size + 1;
2033 if (max_size <= specpdl_size)
2035 if (max_specpdl_size < 400)
2036 max_size = max_specpdl_size = 400;
2037 if (max_size <= specpdl_size)
2038 signal_error ("Variable binding depth exceeds max-specpdl-size",
2039 Qnil);
2041 pdlvec = xpalloc (pdlvec, &pdlvecsize, 1, max_size + 1, sizeof *specpdl);
2042 specpdl = pdlvec + 1;
2043 specpdl_size = pdlvecsize - 1;
2044 specpdl_ptr = specpdl + count;
2048 ptrdiff_t
2049 record_in_backtrace (Lisp_Object function, Lisp_Object *args, ptrdiff_t nargs)
2051 ptrdiff_t count = SPECPDL_INDEX ();
2053 eassert (nargs >= UNEVALLED);
2054 specpdl_ptr->bt.kind = SPECPDL_BACKTRACE;
2055 specpdl_ptr->bt.debug_on_exit = false;
2056 specpdl_ptr->bt.function = function;
2057 specpdl_ptr->bt.args = args;
2058 specpdl_ptr->bt.nargs = nargs;
2059 grow_specpdl ();
2061 return count;
2064 /* Eval a sub-expression of the current expression (i.e. in the same
2065 lexical scope). */
2066 Lisp_Object
2067 eval_sub (Lisp_Object form)
2069 Lisp_Object fun, val, original_fun, original_args;
2070 Lisp_Object funcar;
2071 ptrdiff_t count;
2073 /* Declare here, as this array may be accessed by call_debugger near
2074 the end of this function. See Bug#21245. */
2075 Lisp_Object argvals[8];
2077 if (SYMBOLP (form))
2079 /* Look up its binding in the lexical environment.
2080 We do not pay attention to the declared_special flag here, since we
2081 already did that when let-binding the variable. */
2082 Lisp_Object lex_binding
2083 = !NILP (Vinternal_interpreter_environment) /* Mere optimization! */
2084 ? Fassq (form, Vinternal_interpreter_environment)
2085 : Qnil;
2086 if (CONSP (lex_binding))
2087 return XCDR (lex_binding);
2088 else
2089 return Fsymbol_value (form);
2092 if (!CONSP (form))
2093 return form;
2095 QUIT;
2097 maybe_gc ();
2099 if (++lisp_eval_depth > max_lisp_eval_depth)
2101 if (max_lisp_eval_depth < 100)
2102 max_lisp_eval_depth = 100;
2103 if (lisp_eval_depth > max_lisp_eval_depth)
2104 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2107 original_fun = XCAR (form);
2108 original_args = XCDR (form);
2110 /* This also protects them from gc. */
2111 count = record_in_backtrace (original_fun, &original_args, UNEVALLED);
2113 if (debug_on_next_call)
2114 do_debug_on_call (Qt, count);
2116 /* At this point, only original_fun and original_args
2117 have values that will be used below. */
2118 retry:
2120 /* Optimize for no indirection. */
2121 fun = original_fun;
2122 if (!SYMBOLP (fun))
2123 fun = Ffunction (Fcons (fun, Qnil));
2124 else if (!NILP (fun) && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2125 fun = indirect_function (fun);
2127 if (SUBRP (fun))
2129 Lisp_Object args_left = original_args;
2130 Lisp_Object numargs = Flength (args_left);
2132 check_cons_list ();
2134 if (XINT (numargs) < XSUBR (fun)->min_args
2135 || (XSUBR (fun)->max_args >= 0
2136 && XSUBR (fun)->max_args < XINT (numargs)))
2137 xsignal2 (Qwrong_number_of_arguments, original_fun, numargs);
2139 else if (XSUBR (fun)->max_args == UNEVALLED)
2140 val = (XSUBR (fun)->function.aUNEVALLED) (args_left);
2141 else if (XSUBR (fun)->max_args == MANY)
2143 /* Pass a vector of evaluated arguments. */
2144 Lisp_Object *vals;
2145 ptrdiff_t argnum = 0;
2146 USE_SAFE_ALLOCA;
2148 SAFE_ALLOCA_LISP (vals, XINT (numargs));
2150 while (!NILP (args_left))
2152 vals[argnum++] = eval_sub (Fcar (args_left));
2153 args_left = Fcdr (args_left);
2156 set_backtrace_args (specpdl + count, vals, XINT (numargs));
2158 val = (XSUBR (fun)->function.aMANY) (XINT (numargs), vals);
2160 check_cons_list ();
2161 lisp_eval_depth--;
2162 /* Do the debug-on-exit now, while VALS still exists. */
2163 if (backtrace_debug_on_exit (specpdl + count))
2164 val = call_debugger (list2 (Qexit, val));
2165 SAFE_FREE ();
2166 specpdl_ptr--;
2167 return val;
2169 else
2171 int i, maxargs = XSUBR (fun)->max_args;
2173 for (i = 0; i < maxargs; i++)
2175 argvals[i] = eval_sub (Fcar (args_left));
2176 args_left = Fcdr (args_left);
2179 set_backtrace_args (specpdl + count, argvals, XINT (numargs));
2181 switch (i)
2183 case 0:
2184 val = (XSUBR (fun)->function.a0 ());
2185 break;
2186 case 1:
2187 val = (XSUBR (fun)->function.a1 (argvals[0]));
2188 break;
2189 case 2:
2190 val = (XSUBR (fun)->function.a2 (argvals[0], argvals[1]));
2191 break;
2192 case 3:
2193 val = (XSUBR (fun)->function.a3
2194 (argvals[0], argvals[1], argvals[2]));
2195 break;
2196 case 4:
2197 val = (XSUBR (fun)->function.a4
2198 (argvals[0], argvals[1], argvals[2], argvals[3]));
2199 break;
2200 case 5:
2201 val = (XSUBR (fun)->function.a5
2202 (argvals[0], argvals[1], argvals[2], argvals[3],
2203 argvals[4]));
2204 break;
2205 case 6:
2206 val = (XSUBR (fun)->function.a6
2207 (argvals[0], argvals[1], argvals[2], argvals[3],
2208 argvals[4], argvals[5]));
2209 break;
2210 case 7:
2211 val = (XSUBR (fun)->function.a7
2212 (argvals[0], argvals[1], argvals[2], argvals[3],
2213 argvals[4], argvals[5], argvals[6]));
2214 break;
2216 case 8:
2217 val = (XSUBR (fun)->function.a8
2218 (argvals[0], argvals[1], argvals[2], argvals[3],
2219 argvals[4], argvals[5], argvals[6], argvals[7]));
2220 break;
2222 default:
2223 /* Someone has created a subr that takes more arguments than
2224 is supported by this code. We need to either rewrite the
2225 subr to use a different argument protocol, or add more
2226 cases to this switch. */
2227 emacs_abort ();
2231 else if (COMPILEDP (fun))
2232 return apply_lambda (fun, original_args, count);
2233 else
2235 if (NILP (fun))
2236 xsignal1 (Qvoid_function, original_fun);
2237 if (!CONSP (fun))
2238 xsignal1 (Qinvalid_function, original_fun);
2239 funcar = XCAR (fun);
2240 if (!SYMBOLP (funcar))
2241 xsignal1 (Qinvalid_function, original_fun);
2242 if (EQ (funcar, Qautoload))
2244 Fautoload_do_load (fun, original_fun, Qnil);
2245 goto retry;
2247 if (EQ (funcar, Qmacro))
2249 ptrdiff_t count1 = SPECPDL_INDEX ();
2250 Lisp_Object exp;
2251 /* Bind lexical-binding during expansion of the macro, so the
2252 macro can know reliably if the code it outputs will be
2253 interpreted using lexical-binding or not. */
2254 specbind (Qlexical_binding,
2255 NILP (Vinternal_interpreter_environment) ? Qnil : Qt);
2256 exp = apply1 (Fcdr (fun), original_args);
2257 unbind_to (count1, Qnil);
2258 val = eval_sub (exp);
2260 else if (EQ (funcar, Qlambda)
2261 || EQ (funcar, Qclosure))
2262 return apply_lambda (fun, original_args, count);
2263 else
2264 xsignal1 (Qinvalid_function, original_fun);
2266 check_cons_list ();
2268 lisp_eval_depth--;
2269 if (backtrace_debug_on_exit (specpdl + count))
2270 val = call_debugger (list2 (Qexit, val));
2271 specpdl_ptr--;
2273 return val;
2276 DEFUN ("apply", Fapply, Sapply, 1, MANY, 0,
2277 doc: /* Call FUNCTION with our remaining args, using our last arg as list of args.
2278 Then return the value FUNCTION returns.
2279 Thus, (apply \\='+ 1 2 \\='(3 4)) returns 10.
2280 usage: (apply FUNCTION &rest ARGUMENTS) */)
2281 (ptrdiff_t nargs, Lisp_Object *args)
2283 ptrdiff_t i, numargs, funcall_nargs;
2284 register Lisp_Object *funcall_args = NULL;
2285 register Lisp_Object spread_arg = args[nargs - 1];
2286 Lisp_Object fun = args[0];
2287 Lisp_Object retval;
2288 USE_SAFE_ALLOCA;
2290 CHECK_LIST (spread_arg);
2292 numargs = XINT (Flength (spread_arg));
2294 if (numargs == 0)
2295 return Ffuncall (nargs - 1, args);
2296 else if (numargs == 1)
2298 args [nargs - 1] = XCAR (spread_arg);
2299 return Ffuncall (nargs, args);
2302 numargs += nargs - 2;
2304 /* Optimize for no indirection. */
2305 if (SYMBOLP (fun) && !NILP (fun)
2306 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2308 fun = indirect_function (fun);
2309 if (NILP (fun))
2310 /* Let funcall get the error. */
2311 fun = args[0];
2314 if (SUBRP (fun) && XSUBR (fun)->max_args > numargs
2315 /* Don't hide an error by adding missing arguments. */
2316 && numargs >= XSUBR (fun)->min_args)
2318 /* Avoid making funcall cons up a yet another new vector of arguments
2319 by explicitly supplying nil's for optional values. */
2320 SAFE_ALLOCA_LISP (funcall_args, 1 + XSUBR (fun)->max_args);
2321 memclear (funcall_args + numargs + 1,
2322 (XSUBR (fun)->max_args - numargs) * word_size);
2323 funcall_nargs = 1 + XSUBR (fun)->max_args;
2325 else
2326 { /* We add 1 to numargs because funcall_args includes the
2327 function itself as well as its arguments. */
2328 SAFE_ALLOCA_LISP (funcall_args, 1 + numargs);
2329 funcall_nargs = 1 + numargs;
2332 memcpy (funcall_args, args, nargs * word_size);
2333 /* Spread the last arg we got. Its first element goes in
2334 the slot that it used to occupy, hence this value of I. */
2335 i = nargs - 1;
2336 while (!NILP (spread_arg))
2338 funcall_args [i++] = XCAR (spread_arg);
2339 spread_arg = XCDR (spread_arg);
2342 retval = Ffuncall (funcall_nargs, funcall_args);
2344 SAFE_FREE ();
2345 return retval;
2348 /* Run hook variables in various ways. */
2350 static Lisp_Object
2351 funcall_nil (ptrdiff_t nargs, Lisp_Object *args)
2353 Ffuncall (nargs, args);
2354 return Qnil;
2357 DEFUN ("run-hooks", Frun_hooks, Srun_hooks, 0, MANY, 0,
2358 doc: /* Run each hook in HOOKS.
2359 Each argument should be a symbol, a hook variable.
2360 These symbols are processed in the order specified.
2361 If a hook symbol has a non-nil value, that value may be a function
2362 or a list of functions to be called to run the hook.
2363 If the value is a function, it is called with no arguments.
2364 If it is a list, the elements are called, in order, with no arguments.
2366 Major modes should not use this function directly to run their mode
2367 hook; they should use `run-mode-hooks' instead.
2369 Do not use `make-local-variable' to make a hook variable buffer-local.
2370 Instead, use `add-hook' and specify t for the LOCAL argument.
2371 usage: (run-hooks &rest HOOKS) */)
2372 (ptrdiff_t nargs, Lisp_Object *args)
2374 ptrdiff_t i;
2376 for (i = 0; i < nargs; i++)
2377 run_hook (args[i]);
2379 return Qnil;
2382 DEFUN ("run-hook-with-args", Frun_hook_with_args,
2383 Srun_hook_with_args, 1, MANY, 0,
2384 doc: /* Run HOOK with the specified arguments ARGS.
2385 HOOK should be a symbol, a hook variable. The value of HOOK
2386 may be nil, a function, or a list of functions. Call each
2387 function in order with arguments ARGS. The final return value
2388 is unspecified.
2390 Do not use `make-local-variable' to make a hook variable buffer-local.
2391 Instead, use `add-hook' and specify t for the LOCAL argument.
2392 usage: (run-hook-with-args HOOK &rest ARGS) */)
2393 (ptrdiff_t nargs, Lisp_Object *args)
2395 return run_hook_with_args (nargs, args, funcall_nil);
2398 /* NB this one still documents a specific non-nil return value.
2399 (As did run-hook-with-args and run-hook-with-args-until-failure
2400 until they were changed in 24.1.) */
2401 DEFUN ("run-hook-with-args-until-success", Frun_hook_with_args_until_success,
2402 Srun_hook_with_args_until_success, 1, MANY, 0,
2403 doc: /* Run HOOK with the specified arguments ARGS.
2404 HOOK should be a symbol, a hook variable. The value of HOOK
2405 may be nil, a function, or a list of functions. Call each
2406 function in order with arguments ARGS, stopping at the first
2407 one that returns non-nil, and return that value. Otherwise (if
2408 all functions return nil, or if there are no functions to call),
2409 return nil.
2411 Do not use `make-local-variable' to make a hook variable buffer-local.
2412 Instead, use `add-hook' and specify t for the LOCAL argument.
2413 usage: (run-hook-with-args-until-success HOOK &rest ARGS) */)
2414 (ptrdiff_t nargs, Lisp_Object *args)
2416 return run_hook_with_args (nargs, args, Ffuncall);
2419 static Lisp_Object
2420 funcall_not (ptrdiff_t nargs, Lisp_Object *args)
2422 return NILP (Ffuncall (nargs, args)) ? Qt : Qnil;
2425 DEFUN ("run-hook-with-args-until-failure", Frun_hook_with_args_until_failure,
2426 Srun_hook_with_args_until_failure, 1, MANY, 0,
2427 doc: /* Run HOOK with the specified arguments ARGS.
2428 HOOK should be a symbol, a hook variable. The value of HOOK
2429 may be nil, a function, or a list of functions. Call each
2430 function in order with arguments ARGS, stopping at the first
2431 one that returns nil, and return nil. Otherwise (if all functions
2432 return non-nil, or if there are no functions to call), return non-nil
2433 \(do not rely on the precise return value in this case).
2435 Do not use `make-local-variable' to make a hook variable buffer-local.
2436 Instead, use `add-hook' and specify t for the LOCAL argument.
2437 usage: (run-hook-with-args-until-failure HOOK &rest ARGS) */)
2438 (ptrdiff_t nargs, Lisp_Object *args)
2440 return NILP (run_hook_with_args (nargs, args, funcall_not)) ? Qt : Qnil;
2443 static Lisp_Object
2444 run_hook_wrapped_funcall (ptrdiff_t nargs, Lisp_Object *args)
2446 Lisp_Object tmp = args[0], ret;
2447 args[0] = args[1];
2448 args[1] = tmp;
2449 ret = Ffuncall (nargs, args);
2450 args[1] = args[0];
2451 args[0] = tmp;
2452 return ret;
2455 DEFUN ("run-hook-wrapped", Frun_hook_wrapped, Srun_hook_wrapped, 2, MANY, 0,
2456 doc: /* Run HOOK, passing each function through WRAP-FUNCTION.
2457 I.e. instead of calling each function FUN directly with arguments ARGS,
2458 it calls WRAP-FUNCTION with arguments FUN and ARGS.
2459 As soon as a call to WRAP-FUNCTION returns non-nil, `run-hook-wrapped'
2460 aborts and returns that value.
2461 usage: (run-hook-wrapped HOOK WRAP-FUNCTION &rest ARGS) */)
2462 (ptrdiff_t nargs, Lisp_Object *args)
2464 return run_hook_with_args (nargs, args, run_hook_wrapped_funcall);
2467 /* ARGS[0] should be a hook symbol.
2468 Call each of the functions in the hook value, passing each of them
2469 as arguments all the rest of ARGS (all NARGS - 1 elements).
2470 FUNCALL specifies how to call each function on the hook. */
2472 Lisp_Object
2473 run_hook_with_args (ptrdiff_t nargs, Lisp_Object *args,
2474 Lisp_Object (*funcall) (ptrdiff_t nargs, Lisp_Object *args))
2476 Lisp_Object sym, val, ret = Qnil;
2478 /* If we are dying or still initializing,
2479 don't do anything--it would probably crash if we tried. */
2480 if (NILP (Vrun_hooks))
2481 return Qnil;
2483 sym = args[0];
2484 val = find_symbol_value (sym);
2486 if (EQ (val, Qunbound) || NILP (val))
2487 return ret;
2488 else if (!CONSP (val) || FUNCTIONP (val))
2490 args[0] = val;
2491 return funcall (nargs, args);
2493 else
2495 Lisp_Object global_vals = Qnil;
2497 for (;
2498 CONSP (val) && NILP (ret);
2499 val = XCDR (val))
2501 if (EQ (XCAR (val), Qt))
2503 /* t indicates this hook has a local binding;
2504 it means to run the global binding too. */
2505 global_vals = Fdefault_value (sym);
2506 if (NILP (global_vals)) continue;
2508 if (!CONSP (global_vals) || EQ (XCAR (global_vals), Qlambda))
2510 args[0] = global_vals;
2511 ret = funcall (nargs, args);
2513 else
2515 for (;
2516 CONSP (global_vals) && NILP (ret);
2517 global_vals = XCDR (global_vals))
2519 args[0] = XCAR (global_vals);
2520 /* In a global value, t should not occur. If it does, we
2521 must ignore it to avoid an endless loop. */
2522 if (!EQ (args[0], Qt))
2523 ret = funcall (nargs, args);
2527 else
2529 args[0] = XCAR (val);
2530 ret = funcall (nargs, args);
2534 return ret;
2538 /* Run the hook HOOK, giving each function no args. */
2540 void
2541 run_hook (Lisp_Object hook)
2543 Frun_hook_with_args (1, &hook);
2546 /* Run the hook HOOK, giving each function the two args ARG1 and ARG2. */
2548 void
2549 run_hook_with_args_2 (Lisp_Object hook, Lisp_Object arg1, Lisp_Object arg2)
2551 CALLN (Frun_hook_with_args, hook, arg1, arg2);
2554 /* Apply fn to arg. */
2555 Lisp_Object
2556 apply1 (Lisp_Object fn, Lisp_Object arg)
2558 return NILP (arg) ? Ffuncall (1, &fn) : CALLN (Fapply, fn, arg);
2561 /* Call function fn on no arguments. */
2562 Lisp_Object
2563 call0 (Lisp_Object fn)
2565 return Ffuncall (1, &fn);
2568 /* Call function fn with 1 argument arg1. */
2569 /* ARGSUSED */
2570 Lisp_Object
2571 call1 (Lisp_Object fn, Lisp_Object arg1)
2573 return CALLN (Ffuncall, fn, arg1);
2576 /* Call function fn with 2 arguments arg1, arg2. */
2577 /* ARGSUSED */
2578 Lisp_Object
2579 call2 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2)
2581 return CALLN (Ffuncall, fn, arg1, arg2);
2584 /* Call function fn with 3 arguments arg1, arg2, arg3. */
2585 /* ARGSUSED */
2586 Lisp_Object
2587 call3 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2589 return CALLN (Ffuncall, fn, arg1, arg2, arg3);
2592 /* Call function fn with 4 arguments arg1, arg2, arg3, arg4. */
2593 /* ARGSUSED */
2594 Lisp_Object
2595 call4 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2596 Lisp_Object arg4)
2598 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4);
2601 /* Call function fn with 5 arguments arg1, arg2, arg3, arg4, arg5. */
2602 /* ARGSUSED */
2603 Lisp_Object
2604 call5 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2605 Lisp_Object arg4, Lisp_Object arg5)
2607 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5);
2610 /* Call function fn with 6 arguments arg1, arg2, arg3, arg4, arg5, arg6. */
2611 /* ARGSUSED */
2612 Lisp_Object
2613 call6 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2614 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6)
2616 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6);
2619 /* Call function fn with 7 arguments arg1, arg2, arg3, arg4, arg5, arg6, arg7. */
2620 /* ARGSUSED */
2621 Lisp_Object
2622 call7 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2623 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6, Lisp_Object arg7)
2625 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
2628 DEFUN ("functionp", Ffunctionp, Sfunctionp, 1, 1, 0,
2629 doc: /* Non-nil if OBJECT is a function. */)
2630 (Lisp_Object object)
2632 if (FUNCTIONP (object))
2633 return Qt;
2634 return Qnil;
2637 DEFUN ("funcall", Ffuncall, Sfuncall, 1, MANY, 0,
2638 doc: /* Call first argument as a function, passing remaining arguments to it.
2639 Return the value that function returns.
2640 Thus, (funcall \\='cons \\='x \\='y) returns (x . y).
2641 usage: (funcall FUNCTION &rest ARGUMENTS) */)
2642 (ptrdiff_t nargs, Lisp_Object *args)
2644 Lisp_Object fun, original_fun;
2645 Lisp_Object funcar;
2646 ptrdiff_t numargs = nargs - 1;
2647 Lisp_Object lisp_numargs;
2648 Lisp_Object val;
2649 Lisp_Object *internal_args;
2650 ptrdiff_t count;
2652 QUIT;
2654 if (++lisp_eval_depth > max_lisp_eval_depth)
2656 if (max_lisp_eval_depth < 100)
2657 max_lisp_eval_depth = 100;
2658 if (lisp_eval_depth > max_lisp_eval_depth)
2659 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2662 count = record_in_backtrace (args[0], &args[1], nargs - 1);
2664 maybe_gc ();
2666 if (debug_on_next_call)
2667 do_debug_on_call (Qlambda, count);
2669 check_cons_list ();
2671 original_fun = args[0];
2673 retry:
2675 /* Optimize for no indirection. */
2676 fun = original_fun;
2677 if (SYMBOLP (fun) && !NILP (fun)
2678 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2679 fun = indirect_function (fun);
2681 if (SUBRP (fun))
2683 if (numargs < XSUBR (fun)->min_args
2684 || (XSUBR (fun)->max_args >= 0 && XSUBR (fun)->max_args < numargs))
2686 XSETFASTINT (lisp_numargs, numargs);
2687 xsignal2 (Qwrong_number_of_arguments, original_fun, lisp_numargs);
2690 else if (XSUBR (fun)->max_args == UNEVALLED)
2691 xsignal1 (Qinvalid_function, original_fun);
2693 else if (XSUBR (fun)->max_args == MANY)
2694 val = (XSUBR (fun)->function.aMANY) (numargs, args + 1);
2695 else
2697 Lisp_Object internal_argbuf[8];
2698 if (XSUBR (fun)->max_args > numargs)
2700 eassert (XSUBR (fun)->max_args <= ARRAYELTS (internal_argbuf));
2701 internal_args = internal_argbuf;
2702 memcpy (internal_args, args + 1, numargs * word_size);
2703 memclear (internal_args + numargs,
2704 (XSUBR (fun)->max_args - numargs) * word_size);
2706 else
2707 internal_args = args + 1;
2708 switch (XSUBR (fun)->max_args)
2710 case 0:
2711 val = (XSUBR (fun)->function.a0 ());
2712 break;
2713 case 1:
2714 val = (XSUBR (fun)->function.a1 (internal_args[0]));
2715 break;
2716 case 2:
2717 val = (XSUBR (fun)->function.a2
2718 (internal_args[0], internal_args[1]));
2719 break;
2720 case 3:
2721 val = (XSUBR (fun)->function.a3
2722 (internal_args[0], internal_args[1], internal_args[2]));
2723 break;
2724 case 4:
2725 val = (XSUBR (fun)->function.a4
2726 (internal_args[0], internal_args[1], internal_args[2],
2727 internal_args[3]));
2728 break;
2729 case 5:
2730 val = (XSUBR (fun)->function.a5
2731 (internal_args[0], internal_args[1], internal_args[2],
2732 internal_args[3], internal_args[4]));
2733 break;
2734 case 6:
2735 val = (XSUBR (fun)->function.a6
2736 (internal_args[0], internal_args[1], internal_args[2],
2737 internal_args[3], internal_args[4], internal_args[5]));
2738 break;
2739 case 7:
2740 val = (XSUBR (fun)->function.a7
2741 (internal_args[0], internal_args[1], internal_args[2],
2742 internal_args[3], internal_args[4], internal_args[5],
2743 internal_args[6]));
2744 break;
2746 case 8:
2747 val = (XSUBR (fun)->function.a8
2748 (internal_args[0], internal_args[1], internal_args[2],
2749 internal_args[3], internal_args[4], internal_args[5],
2750 internal_args[6], internal_args[7]));
2751 break;
2753 default:
2755 /* If a subr takes more than 8 arguments without using MANY
2756 or UNEVALLED, we need to extend this function to support it.
2757 Until this is done, there is no way to call the function. */
2758 emacs_abort ();
2762 else if (COMPILEDP (fun))
2763 val = funcall_lambda (fun, numargs, args + 1);
2764 else
2766 if (NILP (fun))
2767 xsignal1 (Qvoid_function, original_fun);
2768 if (!CONSP (fun))
2769 xsignal1 (Qinvalid_function, original_fun);
2770 funcar = XCAR (fun);
2771 if (!SYMBOLP (funcar))
2772 xsignal1 (Qinvalid_function, original_fun);
2773 if (EQ (funcar, Qlambda)
2774 || EQ (funcar, Qclosure))
2775 val = funcall_lambda (fun, numargs, args + 1);
2776 else if (EQ (funcar, Qautoload))
2778 Fautoload_do_load (fun, original_fun, Qnil);
2779 check_cons_list ();
2780 goto retry;
2782 else
2783 xsignal1 (Qinvalid_function, original_fun);
2785 check_cons_list ();
2786 lisp_eval_depth--;
2787 if (backtrace_debug_on_exit (specpdl + count))
2788 val = call_debugger (list2 (Qexit, val));
2789 specpdl_ptr--;
2790 return val;
2793 static Lisp_Object
2794 apply_lambda (Lisp_Object fun, Lisp_Object args, ptrdiff_t count)
2796 Lisp_Object args_left;
2797 ptrdiff_t i;
2798 EMACS_INT numargs;
2799 Lisp_Object *arg_vector;
2800 Lisp_Object tem;
2801 USE_SAFE_ALLOCA;
2803 numargs = XFASTINT (Flength (args));
2804 SAFE_ALLOCA_LISP (arg_vector, numargs);
2805 args_left = args;
2807 for (i = 0; i < numargs; )
2809 tem = Fcar (args_left), args_left = Fcdr (args_left);
2810 tem = eval_sub (tem);
2811 arg_vector[i++] = tem;
2814 set_backtrace_args (specpdl + count, arg_vector, i);
2815 tem = funcall_lambda (fun, numargs, arg_vector);
2817 check_cons_list ();
2818 lisp_eval_depth--;
2819 /* Do the debug-on-exit now, while arg_vector still exists. */
2820 if (backtrace_debug_on_exit (specpdl + count))
2821 tem = call_debugger (list2 (Qexit, tem));
2822 SAFE_FREE ();
2823 specpdl_ptr--;
2824 return tem;
2827 /* Apply a Lisp function FUN to the NARGS evaluated arguments in ARG_VECTOR
2828 and return the result of evaluation.
2829 FUN must be either a lambda-expression or a compiled-code object. */
2831 static Lisp_Object
2832 funcall_lambda (Lisp_Object fun, ptrdiff_t nargs,
2833 register Lisp_Object *arg_vector)
2835 Lisp_Object val, syms_left, next, lexenv;
2836 ptrdiff_t count = SPECPDL_INDEX ();
2837 ptrdiff_t i;
2838 bool optional, rest;
2840 if (CONSP (fun))
2842 if (EQ (XCAR (fun), Qclosure))
2844 fun = XCDR (fun); /* Drop `closure'. */
2845 lexenv = XCAR (fun);
2846 CHECK_LIST_CONS (fun, fun);
2848 else
2849 lexenv = Qnil;
2850 syms_left = XCDR (fun);
2851 if (CONSP (syms_left))
2852 syms_left = XCAR (syms_left);
2853 else
2854 xsignal1 (Qinvalid_function, fun);
2856 else if (COMPILEDP (fun))
2858 ptrdiff_t size = ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK;
2859 if (size <= COMPILED_STACK_DEPTH)
2860 xsignal1 (Qinvalid_function, fun);
2861 syms_left = AREF (fun, COMPILED_ARGLIST);
2862 if (INTEGERP (syms_left))
2863 /* A byte-code object with an integer args template means we
2864 shouldn't bind any arguments, instead just call the byte-code
2865 interpreter directly; it will push arguments as necessary.
2867 Byte-code objects with a nil args template (the default)
2868 have dynamically-bound arguments, and use the
2869 argument-binding code below instead (as do all interpreted
2870 functions, even lexically bound ones). */
2872 /* If we have not actually read the bytecode string
2873 and constants vector yet, fetch them from the file. */
2874 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2875 Ffetch_bytecode (fun);
2876 return exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2877 AREF (fun, COMPILED_CONSTANTS),
2878 AREF (fun, COMPILED_STACK_DEPTH),
2879 syms_left,
2880 nargs, arg_vector);
2882 lexenv = Qnil;
2884 else
2885 emacs_abort ();
2887 i = optional = rest = 0;
2888 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
2890 QUIT;
2892 next = XCAR (syms_left);
2893 if (!SYMBOLP (next))
2894 xsignal1 (Qinvalid_function, fun);
2896 if (EQ (next, Qand_rest))
2897 rest = 1;
2898 else if (EQ (next, Qand_optional))
2899 optional = 1;
2900 else
2902 Lisp_Object arg;
2903 if (rest)
2905 arg = Flist (nargs - i, &arg_vector[i]);
2906 i = nargs;
2908 else if (i < nargs)
2909 arg = arg_vector[i++];
2910 else if (!optional)
2911 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2912 else
2913 arg = Qnil;
2915 /* Bind the argument. */
2916 if (!NILP (lexenv) && SYMBOLP (next))
2917 /* Lexically bind NEXT by adding it to the lexenv alist. */
2918 lexenv = Fcons (Fcons (next, arg), lexenv);
2919 else
2920 /* Dynamically bind NEXT. */
2921 specbind (next, arg);
2925 if (!NILP (syms_left))
2926 xsignal1 (Qinvalid_function, fun);
2927 else if (i < nargs)
2928 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2930 if (!EQ (lexenv, Vinternal_interpreter_environment))
2931 /* Instantiate a new lexical environment. */
2932 specbind (Qinternal_interpreter_environment, lexenv);
2934 if (CONSP (fun))
2935 val = Fprogn (XCDR (XCDR (fun)));
2936 else
2938 /* If we have not actually read the bytecode string
2939 and constants vector yet, fetch them from the file. */
2940 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2941 Ffetch_bytecode (fun);
2942 val = exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2943 AREF (fun, COMPILED_CONSTANTS),
2944 AREF (fun, COMPILED_STACK_DEPTH),
2945 Qnil, 0, 0);
2948 return unbind_to (count, val);
2951 DEFUN ("func-arity", Ffunc_arity, Sfunc_arity, 1, 1, 0,
2952 doc: /* Return minimum and maximum number of args allowed for FUNCTION.
2953 FUNCTION must be a function of some kind.
2954 The returned value is a cons cell (MIN . MAX). MIN is the minimum number
2955 of args. MAX is the maximum number, or the symbol `many', for a
2956 function with `&rest' args, or `unevalled' for a special form. */)
2957 (Lisp_Object function)
2959 Lisp_Object original;
2960 Lisp_Object funcar;
2961 Lisp_Object result;
2963 original = function;
2965 retry:
2967 /* Optimize for no indirection. */
2968 function = original;
2969 if (SYMBOLP (function) && !NILP (function))
2971 function = XSYMBOL (function)->function;
2972 if (SYMBOLP (function))
2973 function = indirect_function (function);
2976 if (CONSP (function) && EQ (XCAR (function), Qmacro))
2977 function = XCDR (function);
2979 if (SUBRP (function))
2980 result = Fsubr_arity (function);
2981 else if (COMPILEDP (function))
2982 result = lambda_arity (function);
2983 else
2985 if (NILP (function))
2986 xsignal1 (Qvoid_function, original);
2987 if (!CONSP (function))
2988 xsignal1 (Qinvalid_function, original);
2989 funcar = XCAR (function);
2990 if (!SYMBOLP (funcar))
2991 xsignal1 (Qinvalid_function, original);
2992 if (EQ (funcar, Qlambda)
2993 || EQ (funcar, Qclosure))
2994 result = lambda_arity (function);
2995 else if (EQ (funcar, Qautoload))
2997 Fautoload_do_load (function, original, Qnil);
2998 goto retry;
3000 else
3001 xsignal1 (Qinvalid_function, original);
3003 return result;
3006 /* FUN must be either a lambda-expression or a compiled-code object. */
3007 static Lisp_Object
3008 lambda_arity (Lisp_Object fun)
3010 Lisp_Object syms_left;
3012 if (CONSP (fun))
3014 if (EQ (XCAR (fun), Qclosure))
3016 fun = XCDR (fun); /* Drop `closure'. */
3017 CHECK_LIST_CONS (fun, fun);
3019 syms_left = XCDR (fun);
3020 if (CONSP (syms_left))
3021 syms_left = XCAR (syms_left);
3022 else
3023 xsignal1 (Qinvalid_function, fun);
3025 else if (COMPILEDP (fun))
3027 ptrdiff_t size = ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK;
3028 if (size <= COMPILED_STACK_DEPTH)
3029 xsignal1 (Qinvalid_function, fun);
3030 syms_left = AREF (fun, COMPILED_ARGLIST);
3031 if (INTEGERP (syms_left))
3032 return get_byte_code_arity (syms_left);
3034 else
3035 emacs_abort ();
3037 EMACS_INT minargs = 0, maxargs = 0;
3038 bool optional = false;
3039 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
3041 Lisp_Object next = XCAR (syms_left);
3042 if (!SYMBOLP (next))
3043 xsignal1 (Qinvalid_function, fun);
3045 if (EQ (next, Qand_rest))
3046 return Fcons (make_number (minargs), Qmany);
3047 else if (EQ (next, Qand_optional))
3048 optional = true;
3049 else
3051 if (!optional)
3052 minargs++;
3053 maxargs++;
3057 if (!NILP (syms_left))
3058 xsignal1 (Qinvalid_function, fun);
3060 return Fcons (make_number (minargs), make_number (maxargs));
3063 DEFUN ("fetch-bytecode", Ffetch_bytecode, Sfetch_bytecode,
3064 1, 1, 0,
3065 doc: /* If byte-compiled OBJECT is lazy-loaded, fetch it now. */)
3066 (Lisp_Object object)
3068 Lisp_Object tem;
3070 if (COMPILEDP (object))
3072 ptrdiff_t size = ASIZE (object) & PSEUDOVECTOR_SIZE_MASK;
3073 if (size <= COMPILED_STACK_DEPTH)
3074 xsignal1 (Qinvalid_function, object);
3075 if (CONSP (AREF (object, COMPILED_BYTECODE)))
3077 tem = read_doc_string (AREF (object, COMPILED_BYTECODE));
3078 if (!CONSP (tem))
3080 tem = AREF (object, COMPILED_BYTECODE);
3081 if (CONSP (tem) && STRINGP (XCAR (tem)))
3082 error ("Invalid byte code in %s", SDATA (XCAR (tem)));
3083 else
3084 error ("Invalid byte code");
3086 ASET (object, COMPILED_BYTECODE, XCAR (tem));
3087 ASET (object, COMPILED_CONSTANTS, XCDR (tem));
3090 return object;
3093 /* Return true if SYMBOL currently has a let-binding
3094 which was made in the buffer that is now current. */
3096 bool
3097 let_shadows_buffer_binding_p (struct Lisp_Symbol *symbol)
3099 union specbinding *p;
3100 Lisp_Object buf = Fcurrent_buffer ();
3102 for (p = specpdl_ptr; p > specpdl; )
3103 if ((--p)->kind > SPECPDL_LET)
3105 struct Lisp_Symbol *let_bound_symbol = XSYMBOL (specpdl_symbol (p));
3106 eassert (let_bound_symbol->redirect != SYMBOL_VARALIAS);
3107 if (symbol == let_bound_symbol
3108 && EQ (specpdl_where (p), buf))
3109 return 1;
3112 return 0;
3115 bool
3116 let_shadows_global_binding_p (Lisp_Object symbol)
3118 union specbinding *p;
3120 for (p = specpdl_ptr; p > specpdl; )
3121 if ((--p)->kind >= SPECPDL_LET && EQ (specpdl_symbol (p), symbol))
3122 return 1;
3124 return 0;
3127 /* `specpdl_ptr' describes which variable is
3128 let-bound, so it can be properly undone when we unbind_to.
3129 It can be either a plain SPECPDL_LET or a SPECPDL_LET_LOCAL/DEFAULT.
3130 - SYMBOL is the variable being bound. Note that it should not be
3131 aliased (i.e. when let-binding V1 that's aliased to V2, we want
3132 to record V2 here).
3133 - WHERE tells us in which buffer the binding took place.
3134 This is used for SPECPDL_LET_LOCAL bindings (i.e. bindings to a
3135 buffer-local variable) as well as for SPECPDL_LET_DEFAULT bindings,
3136 i.e. bindings to the default value of a variable which can be
3137 buffer-local. */
3139 void
3140 specbind (Lisp_Object symbol, Lisp_Object value)
3142 struct Lisp_Symbol *sym;
3144 CHECK_SYMBOL (symbol);
3145 sym = XSYMBOL (symbol);
3147 start:
3148 switch (sym->redirect)
3150 case SYMBOL_VARALIAS:
3151 sym = indirect_variable (sym); XSETSYMBOL (symbol, sym); goto start;
3152 case SYMBOL_PLAINVAL:
3153 /* The most common case is that of a non-constant symbol with a
3154 trivial value. Make that as fast as we can. */
3155 specpdl_ptr->let.kind = SPECPDL_LET;
3156 specpdl_ptr->let.symbol = symbol;
3157 specpdl_ptr->let.old_value = SYMBOL_VAL (sym);
3158 grow_specpdl ();
3159 if (!sym->constant)
3160 SET_SYMBOL_VAL (sym, value);
3161 else
3162 set_internal (symbol, value, Qnil, 1);
3163 break;
3164 case SYMBOL_LOCALIZED:
3165 if (SYMBOL_BLV (sym)->frame_local)
3166 error ("Frame-local vars cannot be let-bound");
3167 case SYMBOL_FORWARDED:
3169 Lisp_Object ovalue = find_symbol_value (symbol);
3170 specpdl_ptr->let.kind = SPECPDL_LET_LOCAL;
3171 specpdl_ptr->let.symbol = symbol;
3172 specpdl_ptr->let.old_value = ovalue;
3173 specpdl_ptr->let.where = Fcurrent_buffer ();
3175 eassert (sym->redirect != SYMBOL_LOCALIZED
3176 || (EQ (SYMBOL_BLV (sym)->where, Fcurrent_buffer ())));
3178 if (sym->redirect == SYMBOL_LOCALIZED)
3180 if (!blv_found (SYMBOL_BLV (sym)))
3181 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3183 else if (BUFFER_OBJFWDP (SYMBOL_FWD (sym)))
3185 /* If SYMBOL is a per-buffer variable which doesn't have a
3186 buffer-local value here, make the `let' change the global
3187 value by changing the value of SYMBOL in all buffers not
3188 having their own value. This is consistent with what
3189 happens with other buffer-local variables. */
3190 if (NILP (Flocal_variable_p (symbol, Qnil)))
3192 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3193 grow_specpdl ();
3194 Fset_default (symbol, value);
3195 return;
3198 else
3199 specpdl_ptr->let.kind = SPECPDL_LET;
3201 grow_specpdl ();
3202 set_internal (symbol, value, Qnil, 1);
3203 break;
3205 default: emacs_abort ();
3209 /* Push unwind-protect entries of various types. */
3211 void
3212 record_unwind_protect (void (*function) (Lisp_Object), Lisp_Object arg)
3214 specpdl_ptr->unwind.kind = SPECPDL_UNWIND;
3215 specpdl_ptr->unwind.func = function;
3216 specpdl_ptr->unwind.arg = arg;
3217 grow_specpdl ();
3220 void
3221 record_unwind_protect_ptr (void (*function) (void *), void *arg)
3223 specpdl_ptr->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3224 specpdl_ptr->unwind_ptr.func = function;
3225 specpdl_ptr->unwind_ptr.arg = arg;
3226 grow_specpdl ();
3229 void
3230 record_unwind_protect_int (void (*function) (int), int arg)
3232 specpdl_ptr->unwind_int.kind = SPECPDL_UNWIND_INT;
3233 specpdl_ptr->unwind_int.func = function;
3234 specpdl_ptr->unwind_int.arg = arg;
3235 grow_specpdl ();
3238 void
3239 record_unwind_protect_void (void (*function) (void))
3241 specpdl_ptr->unwind_void.kind = SPECPDL_UNWIND_VOID;
3242 specpdl_ptr->unwind_void.func = function;
3243 grow_specpdl ();
3246 static void
3247 do_nothing (void)
3250 /* Push an unwind-protect entry that does nothing, so that
3251 set_unwind_protect_ptr can overwrite it later. */
3253 void
3254 record_unwind_protect_nothing (void)
3256 record_unwind_protect_void (do_nothing);
3259 /* Clear the unwind-protect entry COUNT, so that it does nothing.
3260 It need not be at the top of the stack. */
3262 void
3263 clear_unwind_protect (ptrdiff_t count)
3265 union specbinding *p = specpdl + count;
3266 p->unwind_void.kind = SPECPDL_UNWIND_VOID;
3267 p->unwind_void.func = do_nothing;
3270 /* Set the unwind-protect entry COUNT so that it invokes FUNC (ARG).
3271 It need not be at the top of the stack. Discard the entry's
3272 previous value without invoking it. */
3274 void
3275 set_unwind_protect (ptrdiff_t count, void (*func) (Lisp_Object),
3276 Lisp_Object arg)
3278 union specbinding *p = specpdl + count;
3279 p->unwind.kind = SPECPDL_UNWIND;
3280 p->unwind.func = func;
3281 p->unwind.arg = arg;
3284 void
3285 set_unwind_protect_ptr (ptrdiff_t count, void (*func) (void *), void *arg)
3287 union specbinding *p = specpdl + count;
3288 p->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3289 p->unwind_ptr.func = func;
3290 p->unwind_ptr.arg = arg;
3293 /* Pop and execute entries from the unwind-protect stack until the
3294 depth COUNT is reached. Return VALUE. */
3296 Lisp_Object
3297 unbind_to (ptrdiff_t count, Lisp_Object value)
3299 Lisp_Object quitf = Vquit_flag;
3301 Vquit_flag = Qnil;
3303 while (specpdl_ptr != specpdl + count)
3305 /* Decrement specpdl_ptr before we do the work to unbind it, so
3306 that an error in unbinding won't try to unbind the same entry
3307 again. Take care to copy any parts of the binding needed
3308 before invoking any code that can make more bindings. */
3310 specpdl_ptr--;
3312 switch (specpdl_ptr->kind)
3314 case SPECPDL_UNWIND:
3315 specpdl_ptr->unwind.func (specpdl_ptr->unwind.arg);
3316 break;
3317 case SPECPDL_UNWIND_PTR:
3318 specpdl_ptr->unwind_ptr.func (specpdl_ptr->unwind_ptr.arg);
3319 break;
3320 case SPECPDL_UNWIND_INT:
3321 specpdl_ptr->unwind_int.func (specpdl_ptr->unwind_int.arg);
3322 break;
3323 case SPECPDL_UNWIND_VOID:
3324 specpdl_ptr->unwind_void.func ();
3325 break;
3326 case SPECPDL_BACKTRACE:
3327 break;
3328 case SPECPDL_LET:
3329 { /* If variable has a trivial value (no forwarding), we can
3330 just set it. No need to check for constant symbols here,
3331 since that was already done by specbind. */
3332 Lisp_Object sym = specpdl_symbol (specpdl_ptr);
3333 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3335 SET_SYMBOL_VAL (XSYMBOL (sym),
3336 specpdl_old_value (specpdl_ptr));
3337 break;
3339 else
3340 { /* FALLTHROUGH!!
3341 NOTE: we only ever come here if make_local_foo was used for
3342 the first time on this var within this let. */
3345 case SPECPDL_LET_DEFAULT:
3346 Fset_default (specpdl_symbol (specpdl_ptr),
3347 specpdl_old_value (specpdl_ptr));
3348 break;
3349 case SPECPDL_LET_LOCAL:
3351 Lisp_Object symbol = specpdl_symbol (specpdl_ptr);
3352 Lisp_Object where = specpdl_where (specpdl_ptr);
3353 Lisp_Object old_value = specpdl_old_value (specpdl_ptr);
3354 eassert (BUFFERP (where));
3356 /* If this was a local binding, reset the value in the appropriate
3357 buffer, but only if that buffer's binding still exists. */
3358 if (!NILP (Flocal_variable_p (symbol, where)))
3359 set_internal (symbol, old_value, where, 1);
3361 break;
3365 if (NILP (Vquit_flag) && !NILP (quitf))
3366 Vquit_flag = quitf;
3368 return value;
3371 DEFUN ("special-variable-p", Fspecial_variable_p, Sspecial_variable_p, 1, 1, 0,
3372 doc: /* Return non-nil if SYMBOL's global binding has been declared special.
3373 A special variable is one that will be bound dynamically, even in a
3374 context where binding is lexical by default. */)
3375 (Lisp_Object symbol)
3377 CHECK_SYMBOL (symbol);
3378 return XSYMBOL (symbol)->declared_special ? Qt : Qnil;
3382 DEFUN ("backtrace-debug", Fbacktrace_debug, Sbacktrace_debug, 2, 2, 0,
3383 doc: /* Set the debug-on-exit flag of eval frame LEVEL levels down to FLAG.
3384 The debugger is entered when that frame exits, if the flag is non-nil. */)
3385 (Lisp_Object level, Lisp_Object flag)
3387 union specbinding *pdl = backtrace_top ();
3388 register EMACS_INT i;
3390 CHECK_NUMBER (level);
3392 for (i = 0; backtrace_p (pdl) && i < XINT (level); i++)
3393 pdl = backtrace_next (pdl);
3395 if (backtrace_p (pdl))
3396 set_backtrace_debug_on_exit (pdl, !NILP (flag));
3398 return flag;
3401 DEFUN ("backtrace", Fbacktrace, Sbacktrace, 0, 0, "",
3402 doc: /* Print a trace of Lisp function calls currently active.
3403 Output stream used is value of `standard-output'. */)
3404 (void)
3406 union specbinding *pdl = backtrace_top ();
3407 Lisp_Object tem;
3408 Lisp_Object old_print_level = Vprint_level;
3410 if (NILP (Vprint_level))
3411 XSETFASTINT (Vprint_level, 8);
3413 while (backtrace_p (pdl))
3415 write_string (backtrace_debug_on_exit (pdl) ? "* " : " ");
3416 if (backtrace_nargs (pdl) == UNEVALLED)
3418 Fprin1 (Fcons (backtrace_function (pdl), *backtrace_args (pdl)),
3419 Qnil);
3420 write_string ("\n");
3422 else
3424 tem = backtrace_function (pdl);
3425 Fprin1 (tem, Qnil); /* This can QUIT. */
3426 write_string ("(");
3428 ptrdiff_t i;
3429 for (i = 0; i < backtrace_nargs (pdl); i++)
3431 if (i) write_string (" ");
3432 Fprin1 (backtrace_args (pdl)[i], Qnil);
3435 write_string (")\n");
3437 pdl = backtrace_next (pdl);
3440 Vprint_level = old_print_level;
3441 return Qnil;
3444 static union specbinding *
3445 get_backtrace_frame (Lisp_Object nframes, Lisp_Object base)
3447 union specbinding *pdl = backtrace_top ();
3448 register EMACS_INT i;
3450 CHECK_NATNUM (nframes);
3452 if (!NILP (base))
3453 { /* Skip up to `base'. */
3454 base = Findirect_function (base, Qt);
3455 while (backtrace_p (pdl)
3456 && !EQ (base, Findirect_function (backtrace_function (pdl), Qt)))
3457 pdl = backtrace_next (pdl);
3460 /* Find the frame requested. */
3461 for (i = XFASTINT (nframes); i > 0 && backtrace_p (pdl); i--)
3462 pdl = backtrace_next (pdl);
3464 return pdl;
3467 DEFUN ("backtrace-frame", Fbacktrace_frame, Sbacktrace_frame, 1, 2, NULL,
3468 doc: /* Return the function and arguments NFRAMES up from current execution point.
3469 If that frame has not evaluated the arguments yet (or is a special form),
3470 the value is (nil FUNCTION ARG-FORMS...).
3471 If that frame has evaluated its arguments and called its function already,
3472 the value is (t FUNCTION ARG-VALUES...).
3473 A &rest arg is represented as the tail of the list ARG-VALUES.
3474 FUNCTION is whatever was supplied as car of evaluated list,
3475 or a lambda expression for macro calls.
3476 If NFRAMES is more than the number of frames, the value is nil.
3477 If BASE is non-nil, it should be a function and NFRAMES counts from its
3478 nearest activation frame. */)
3479 (Lisp_Object nframes, Lisp_Object base)
3481 union specbinding *pdl = get_backtrace_frame (nframes, base);
3483 if (!backtrace_p (pdl))
3484 return Qnil;
3485 if (backtrace_nargs (pdl) == UNEVALLED)
3486 return Fcons (Qnil,
3487 Fcons (backtrace_function (pdl), *backtrace_args (pdl)));
3488 else
3490 Lisp_Object tem = Flist (backtrace_nargs (pdl), backtrace_args (pdl));
3492 return Fcons (Qt, Fcons (backtrace_function (pdl), tem));
3496 /* For backtrace-eval, we want to temporarily unwind the last few elements of
3497 the specpdl stack, and then rewind them. We store the pre-unwind values
3498 directly in the pre-existing specpdl elements (i.e. we swap the current
3499 value and the old value stored in the specpdl), kind of like the inplace
3500 pointer-reversal trick. As it turns out, the rewind does the same as the
3501 unwind, except it starts from the other end of the specpdl stack, so we use
3502 the same function for both unwind and rewind. */
3503 static void
3504 backtrace_eval_unrewind (int distance)
3506 union specbinding *tmp = specpdl_ptr;
3507 int step = -1;
3508 if (distance < 0)
3509 { /* It's a rewind rather than unwind. */
3510 tmp += distance - 1;
3511 step = 1;
3512 distance = -distance;
3515 for (; distance > 0; distance--)
3517 tmp += step;
3518 switch (tmp->kind)
3520 /* FIXME: Ideally we'd like to "temporarily unwind" (some of) those
3521 unwind_protect, but the problem is that we don't know how to
3522 rewind them afterwards. */
3523 case SPECPDL_UNWIND:
3525 Lisp_Object oldarg = tmp->unwind.arg;
3526 if (tmp->unwind.func == set_buffer_if_live)
3527 tmp->unwind.arg = Fcurrent_buffer ();
3528 else if (tmp->unwind.func == save_excursion_restore)
3529 tmp->unwind.arg = save_excursion_save ();
3530 else
3531 break;
3532 tmp->unwind.func (oldarg);
3533 break;
3536 case SPECPDL_UNWIND_PTR:
3537 case SPECPDL_UNWIND_INT:
3538 case SPECPDL_UNWIND_VOID:
3539 case SPECPDL_BACKTRACE:
3540 break;
3541 case SPECPDL_LET:
3542 { /* If variable has a trivial value (no forwarding), we can
3543 just set it. No need to check for constant symbols here,
3544 since that was already done by specbind. */
3545 Lisp_Object sym = specpdl_symbol (tmp);
3546 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3548 Lisp_Object old_value = specpdl_old_value (tmp);
3549 set_specpdl_old_value (tmp, SYMBOL_VAL (XSYMBOL (sym)));
3550 SET_SYMBOL_VAL (XSYMBOL (sym), old_value);
3551 break;
3553 else
3554 { /* FALLTHROUGH!!
3555 NOTE: we only ever come here if make_local_foo was used for
3556 the first time on this var within this let. */
3559 case SPECPDL_LET_DEFAULT:
3561 Lisp_Object sym = specpdl_symbol (tmp);
3562 Lisp_Object old_value = specpdl_old_value (tmp);
3563 set_specpdl_old_value (tmp, Fdefault_value (sym));
3564 Fset_default (sym, old_value);
3566 break;
3567 case SPECPDL_LET_LOCAL:
3569 Lisp_Object symbol = specpdl_symbol (tmp);
3570 Lisp_Object where = specpdl_where (tmp);
3571 Lisp_Object old_value = specpdl_old_value (tmp);
3572 eassert (BUFFERP (where));
3574 /* If this was a local binding, reset the value in the appropriate
3575 buffer, but only if that buffer's binding still exists. */
3576 if (!NILP (Flocal_variable_p (symbol, where)))
3578 set_specpdl_old_value
3579 (tmp, Fbuffer_local_value (symbol, where));
3580 set_internal (symbol, old_value, where, 1);
3583 break;
3588 DEFUN ("backtrace-eval", Fbacktrace_eval, Sbacktrace_eval, 2, 3, NULL,
3589 doc: /* Evaluate EXP in the context of some activation frame.
3590 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3591 (Lisp_Object exp, Lisp_Object nframes, Lisp_Object base)
3593 union specbinding *pdl = get_backtrace_frame (nframes, base);
3594 ptrdiff_t count = SPECPDL_INDEX ();
3595 ptrdiff_t distance = specpdl_ptr - pdl;
3596 eassert (distance >= 0);
3598 if (!backtrace_p (pdl))
3599 error ("Activation frame not found!");
3601 backtrace_eval_unrewind (distance);
3602 record_unwind_protect_int (backtrace_eval_unrewind, -distance);
3604 /* Use eval_sub rather than Feval since the main motivation behind
3605 backtrace-eval is to be able to get/set the value of lexical variables
3606 from the debugger. */
3607 return unbind_to (count, eval_sub (exp));
3610 DEFUN ("backtrace--locals", Fbacktrace__locals, Sbacktrace__locals, 1, 2, NULL,
3611 doc: /* Return names and values of local variables of a stack frame.
3612 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3613 (Lisp_Object nframes, Lisp_Object base)
3615 union specbinding *frame = get_backtrace_frame (nframes, base);
3616 union specbinding *prevframe
3617 = get_backtrace_frame (make_number (XFASTINT (nframes) - 1), base);
3618 ptrdiff_t distance = specpdl_ptr - frame;
3619 Lisp_Object result = Qnil;
3620 eassert (distance >= 0);
3622 if (!backtrace_p (prevframe))
3623 error ("Activation frame not found!");
3624 if (!backtrace_p (frame))
3625 error ("Activation frame not found!");
3627 /* The specpdl entries normally contain the symbol being bound along with its
3628 `old_value', so it can be restored. The new value to which it is bound is
3629 available in one of two places: either in the current value of the
3630 variable (if it hasn't been rebound yet) or in the `old_value' slot of the
3631 next specpdl entry for it.
3632 `backtrace_eval_unrewind' happens to swap the role of `old_value'
3633 and "new value", so we abuse it here, to fetch the new value.
3634 It's ugly (we'd rather not modify global data) and a bit inefficient,
3635 but it does the job for now. */
3636 backtrace_eval_unrewind (distance);
3638 /* Grab values. */
3640 union specbinding *tmp = prevframe;
3641 for (; tmp > frame; tmp--)
3643 switch (tmp->kind)
3645 case SPECPDL_LET:
3646 case SPECPDL_LET_DEFAULT:
3647 case SPECPDL_LET_LOCAL:
3649 Lisp_Object sym = specpdl_symbol (tmp);
3650 Lisp_Object val = specpdl_old_value (tmp);
3651 if (EQ (sym, Qinternal_interpreter_environment))
3653 Lisp_Object env = val;
3654 for (; CONSP (env); env = XCDR (env))
3656 Lisp_Object binding = XCAR (env);
3657 if (CONSP (binding))
3658 result = Fcons (Fcons (XCAR (binding),
3659 XCDR (binding)),
3660 result);
3663 else
3664 result = Fcons (Fcons (sym, val), result);
3666 break;
3668 case SPECPDL_UNWIND:
3669 case SPECPDL_UNWIND_PTR:
3670 case SPECPDL_UNWIND_INT:
3671 case SPECPDL_UNWIND_VOID:
3672 case SPECPDL_BACKTRACE:
3673 break;
3675 default:
3676 emacs_abort ();
3681 /* Restore values from specpdl to original place. */
3682 backtrace_eval_unrewind (-distance);
3684 return result;
3688 void
3689 mark_specpdl (void)
3691 union specbinding *pdl;
3692 for (pdl = specpdl; pdl != specpdl_ptr; pdl++)
3694 switch (pdl->kind)
3696 case SPECPDL_UNWIND:
3697 mark_object (specpdl_arg (pdl));
3698 break;
3700 case SPECPDL_BACKTRACE:
3702 ptrdiff_t nargs = backtrace_nargs (pdl);
3703 mark_object (backtrace_function (pdl));
3704 if (nargs == UNEVALLED)
3705 nargs = 1;
3706 while (nargs--)
3707 mark_object (backtrace_args (pdl)[nargs]);
3709 break;
3711 case SPECPDL_LET_DEFAULT:
3712 case SPECPDL_LET_LOCAL:
3713 mark_object (specpdl_where (pdl));
3714 /* Fall through. */
3715 case SPECPDL_LET:
3716 mark_object (specpdl_symbol (pdl));
3717 mark_object (specpdl_old_value (pdl));
3718 break;
3720 case SPECPDL_UNWIND_PTR:
3721 case SPECPDL_UNWIND_INT:
3722 case SPECPDL_UNWIND_VOID:
3723 break;
3725 default:
3726 emacs_abort ();
3731 void
3732 get_backtrace (Lisp_Object array)
3734 union specbinding *pdl = backtrace_next (backtrace_top ());
3735 ptrdiff_t i = 0, asize = ASIZE (array);
3737 /* Copy the backtrace contents into working memory. */
3738 for (; i < asize; i++)
3740 if (backtrace_p (pdl))
3742 ASET (array, i, backtrace_function (pdl));
3743 pdl = backtrace_next (pdl);
3745 else
3746 ASET (array, i, Qnil);
3750 Lisp_Object backtrace_top_function (void)
3752 union specbinding *pdl = backtrace_top ();
3753 return (backtrace_p (pdl) ? backtrace_function (pdl) : Qnil);
3756 void
3757 syms_of_eval (void)
3759 DEFVAR_INT ("max-specpdl-size", max_specpdl_size,
3760 doc: /* Limit on number of Lisp variable bindings and `unwind-protect's.
3761 If Lisp code tries to increase the total number past this amount,
3762 an error is signaled.
3763 You can safely use a value considerably larger than the default value,
3764 if that proves inconveniently small. However, if you increase it too far,
3765 Emacs could run out of memory trying to make the stack bigger.
3766 Note that this limit may be silently increased by the debugger
3767 if `debug-on-error' or `debug-on-quit' is set. */);
3769 DEFVAR_INT ("max-lisp-eval-depth", max_lisp_eval_depth,
3770 doc: /* Limit on depth in `eval', `apply' and `funcall' before error.
3772 This limit serves to catch infinite recursions for you before they cause
3773 actual stack overflow in C, which would be fatal for Emacs.
3774 You can safely make it considerably larger than its default value,
3775 if that proves inconveniently small. However, if you increase it too far,
3776 Emacs could overflow the real C stack, and crash. */);
3778 DEFVAR_LISP ("quit-flag", Vquit_flag,
3779 doc: /* Non-nil causes `eval' to abort, unless `inhibit-quit' is non-nil.
3780 If the value is t, that means do an ordinary quit.
3781 If the value equals `throw-on-input', that means quit by throwing
3782 to the tag specified in `throw-on-input'; it's for handling `while-no-input'.
3783 Typing C-g sets `quit-flag' to t, regardless of `inhibit-quit',
3784 but `inhibit-quit' non-nil prevents anything from taking notice of that. */);
3785 Vquit_flag = Qnil;
3787 DEFVAR_LISP ("inhibit-quit", Vinhibit_quit,
3788 doc: /* Non-nil inhibits C-g quitting from happening immediately.
3789 Note that `quit-flag' will still be set by typing C-g,
3790 so a quit will be signaled as soon as `inhibit-quit' is nil.
3791 To prevent this happening, set `quit-flag' to nil
3792 before making `inhibit-quit' nil. */);
3793 Vinhibit_quit = Qnil;
3795 DEFSYM (Qsetq, "setq");
3796 DEFSYM (Qinhibit_quit, "inhibit-quit");
3797 DEFSYM (Qautoload, "autoload");
3798 DEFSYM (Qinhibit_debugger, "inhibit-debugger");
3799 DEFSYM (Qmacro, "macro");
3801 /* Note that the process handling also uses Qexit, but we don't want
3802 to staticpro it twice, so we just do it here. */
3803 DEFSYM (Qexit, "exit");
3805 DEFSYM (Qinteractive, "interactive");
3806 DEFSYM (Qcommandp, "commandp");
3807 DEFSYM (Qand_rest, "&rest");
3808 DEFSYM (Qand_optional, "&optional");
3809 DEFSYM (Qclosure, "closure");
3810 DEFSYM (QCdocumentation, ":documentation");
3811 DEFSYM (Qdebug, "debug");
3813 DEFVAR_LISP ("inhibit-debugger", Vinhibit_debugger,
3814 doc: /* Non-nil means never enter the debugger.
3815 Normally set while the debugger is already active, to avoid recursive
3816 invocations. */);
3817 Vinhibit_debugger = Qnil;
3819 DEFVAR_LISP ("debug-on-error", Vdebug_on_error,
3820 doc: /* Non-nil means enter debugger if an error is signaled.
3821 Does not apply to errors handled by `condition-case' or those
3822 matched by `debug-ignored-errors'.
3823 If the value is a list, an error only means to enter the debugger
3824 if one of its condition symbols appears in the list.
3825 When you evaluate an expression interactively, this variable
3826 is temporarily non-nil if `eval-expression-debug-on-error' is non-nil.
3827 The command `toggle-debug-on-error' toggles this.
3828 See also the variable `debug-on-quit' and `inhibit-debugger'. */);
3829 Vdebug_on_error = Qnil;
3831 DEFVAR_LISP ("debug-ignored-errors", Vdebug_ignored_errors,
3832 doc: /* List of errors for which the debugger should not be called.
3833 Each element may be a condition-name or a regexp that matches error messages.
3834 If any element applies to a given error, that error skips the debugger
3835 and just returns to top level.
3836 This overrides the variable `debug-on-error'.
3837 It does not apply to errors handled by `condition-case'. */);
3838 Vdebug_ignored_errors = Qnil;
3840 DEFVAR_BOOL ("debug-on-quit", debug_on_quit,
3841 doc: /* Non-nil means enter debugger if quit is signaled (C-g, for example).
3842 Does not apply if quit is handled by a `condition-case'. */);
3843 debug_on_quit = 0;
3845 DEFVAR_BOOL ("debug-on-next-call", debug_on_next_call,
3846 doc: /* Non-nil means enter debugger before next `eval', `apply' or `funcall'. */);
3848 DEFVAR_BOOL ("debugger-may-continue", debugger_may_continue,
3849 doc: /* Non-nil means debugger may continue execution.
3850 This is nil when the debugger is called under circumstances where it
3851 might not be safe to continue. */);
3852 debugger_may_continue = 1;
3854 DEFVAR_LISP ("debugger", Vdebugger,
3855 doc: /* Function to call to invoke debugger.
3856 If due to frame exit, args are `exit' and the value being returned;
3857 this function's value will be returned instead of that.
3858 If due to error, args are `error' and a list of the args to `signal'.
3859 If due to `apply' or `funcall' entry, one arg, `lambda'.
3860 If due to `eval' entry, one arg, t. */);
3861 Vdebugger = Qnil;
3863 DEFVAR_LISP ("signal-hook-function", Vsignal_hook_function,
3864 doc: /* If non-nil, this is a function for `signal' to call.
3865 It receives the same arguments that `signal' was given.
3866 The Edebug package uses this to regain control. */);
3867 Vsignal_hook_function = Qnil;
3869 DEFVAR_LISP ("debug-on-signal", Vdebug_on_signal,
3870 doc: /* Non-nil means call the debugger regardless of condition handlers.
3871 Note that `debug-on-error', `debug-on-quit' and friends
3872 still determine whether to handle the particular condition. */);
3873 Vdebug_on_signal = Qnil;
3875 /* When lexical binding is being used,
3876 Vinternal_interpreter_environment is non-nil, and contains an alist
3877 of lexically-bound variable, or (t), indicating an empty
3878 environment. The lisp name of this variable would be
3879 `internal-interpreter-environment' if it weren't hidden.
3880 Every element of this list can be either a cons (VAR . VAL)
3881 specifying a lexical binding, or a single symbol VAR indicating
3882 that this variable should use dynamic scoping. */
3883 DEFSYM (Qinternal_interpreter_environment,
3884 "internal-interpreter-environment");
3885 DEFVAR_LISP ("internal-interpreter-environment",
3886 Vinternal_interpreter_environment,
3887 doc: /* If non-nil, the current lexical environment of the lisp interpreter.
3888 When lexical binding is not being used, this variable is nil.
3889 A value of `(t)' indicates an empty environment, otherwise it is an
3890 alist of active lexical bindings. */);
3891 Vinternal_interpreter_environment = Qnil;
3892 /* Don't export this variable to Elisp, so no one can mess with it
3893 (Just imagine if someone makes it buffer-local). */
3894 Funintern (Qinternal_interpreter_environment, Qnil);
3896 Vrun_hooks = intern_c_string ("run-hooks");
3897 staticpro (&Vrun_hooks);
3899 staticpro (&Vautoload_queue);
3900 Vautoload_queue = Qnil;
3901 staticpro (&Vsignaling_function);
3902 Vsignaling_function = Qnil;
3904 inhibit_lisp_code = Qnil;
3906 defsubr (&Sor);
3907 defsubr (&Sand);
3908 defsubr (&Sif);
3909 defsubr (&Scond);
3910 defsubr (&Sprogn);
3911 defsubr (&Sprog1);
3912 defsubr (&Sprog2);
3913 defsubr (&Ssetq);
3914 defsubr (&Squote);
3915 defsubr (&Sfunction);
3916 defsubr (&Sdefault_toplevel_value);
3917 defsubr (&Sset_default_toplevel_value);
3918 defsubr (&Sdefvar);
3919 defsubr (&Sdefvaralias);
3920 defsubr (&Sdefconst);
3921 defsubr (&Smake_var_non_special);
3922 defsubr (&Slet);
3923 defsubr (&SletX);
3924 defsubr (&Swhile);
3925 defsubr (&Smacroexpand);
3926 defsubr (&Scatch);
3927 defsubr (&Sthrow);
3928 defsubr (&Sunwind_protect);
3929 defsubr (&Scondition_case);
3930 defsubr (&Ssignal);
3931 defsubr (&Scommandp);
3932 defsubr (&Sautoload);
3933 defsubr (&Sautoload_do_load);
3934 defsubr (&Seval);
3935 defsubr (&Sapply);
3936 defsubr (&Sfuncall);
3937 defsubr (&Sfunc_arity);
3938 defsubr (&Srun_hooks);
3939 defsubr (&Srun_hook_with_args);
3940 defsubr (&Srun_hook_with_args_until_success);
3941 defsubr (&Srun_hook_with_args_until_failure);
3942 defsubr (&Srun_hook_wrapped);
3943 defsubr (&Sfetch_bytecode);
3944 defsubr (&Sbacktrace_debug);
3945 defsubr (&Sbacktrace);
3946 defsubr (&Sbacktrace_frame);
3947 defsubr (&Sbacktrace_eval);
3948 defsubr (&Sbacktrace__locals);
3949 defsubr (&Sspecial_variable_p);
3950 defsubr (&Sfunctionp);