Merge from emacs-24
[emacs.git] / src / eval.c
blob8194468a650d33c756d9f03fe4da2f19b12abc78
1 /* Evaluator for GNU Emacs Lisp interpreter.
3 Copyright (C) 1985-1987, 1993-1995, 1999-2014 Free Software Foundation,
4 Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
23 #include <limits.h>
24 #include <stdio.h>
25 #include "lisp.h"
26 #include "blockinput.h"
27 #include "commands.h"
28 #include "keyboard.h"
29 #include "dispextern.h"
30 #include "buffer.h"
32 /* Chain of condition and catch handlers currently in effect. */
34 struct handler *handlerlist;
36 #ifdef DEBUG_GCPRO
37 /* Count levels of GCPRO to detect failure to UNGCPRO. */
38 int gcpro_level;
39 #endif
41 Lisp_Object Qautoload, Qmacro, Qexit, Qinteractive, Qcommandp;
42 Lisp_Object Qinhibit_quit;
43 Lisp_Object Qand_rest;
44 static Lisp_Object Qand_optional;
45 static Lisp_Object Qinhibit_debugger;
46 static Lisp_Object Qdeclare;
47 Lisp_Object Qinternal_interpreter_environment, Qclosure;
49 static Lisp_Object Qdebug;
51 /* This holds either the symbol `run-hooks' or nil.
52 It is nil at an early stage of startup, and when Emacs
53 is shutting down. */
55 Lisp_Object Vrun_hooks;
57 /* Non-nil means record all fset's and provide's, to be undone
58 if the file being autoloaded is not fully loaded.
59 They are recorded by being consed onto the front of Vautoload_queue:
60 (FUN . ODEF) for a defun, (0 . OFEATURES) for a provide. */
62 Lisp_Object Vautoload_queue;
64 /* Current number of specbindings allocated in specpdl, not counting
65 the dummy entry specpdl[-1]. */
67 ptrdiff_t specpdl_size;
69 /* Pointer to beginning of specpdl. A dummy entry specpdl[-1] exists
70 only so that its address can be taken. */
72 union specbinding *specpdl;
74 /* Pointer to first unused element in specpdl. */
76 union specbinding *specpdl_ptr;
78 /* Depth in Lisp evaluations and function calls. */
80 EMACS_INT lisp_eval_depth;
82 /* The value of num_nonmacro_input_events as of the last time we
83 started to enter the debugger. If we decide to enter the debugger
84 again when this is still equal to num_nonmacro_input_events, then we
85 know that the debugger itself has an error, and we should just
86 signal the error instead of entering an infinite loop of debugger
87 invocations. */
89 static EMACS_INT when_entered_debugger;
91 /* The function from which the last `signal' was called. Set in
92 Fsignal. */
93 /* FIXME: We should probably get rid of this! */
94 Lisp_Object Vsignaling_function;
96 /* If non-nil, Lisp code must not be run since some part of Emacs is in
97 an inconsistent state. Currently unused. */
98 Lisp_Object inhibit_lisp_code;
100 /* These would ordinarily be static, but they need to be visible to GDB. */
101 bool backtrace_p (union specbinding *) EXTERNALLY_VISIBLE;
102 Lisp_Object *backtrace_args (union specbinding *) EXTERNALLY_VISIBLE;
103 Lisp_Object backtrace_function (union specbinding *) EXTERNALLY_VISIBLE;
104 union specbinding *backtrace_next (union specbinding *) EXTERNALLY_VISIBLE;
105 union specbinding *backtrace_top (void) EXTERNALLY_VISIBLE;
107 static Lisp_Object funcall_lambda (Lisp_Object, ptrdiff_t, Lisp_Object *);
108 static Lisp_Object apply_lambda (Lisp_Object, Lisp_Object, ptrdiff_t);
110 static Lisp_Object
111 specpdl_symbol (union specbinding *pdl)
113 eassert (pdl->kind >= SPECPDL_LET);
114 return pdl->let.symbol;
117 static Lisp_Object
118 specpdl_old_value (union specbinding *pdl)
120 eassert (pdl->kind >= SPECPDL_LET);
121 return pdl->let.old_value;
124 static void
125 set_specpdl_old_value (union specbinding *pdl, Lisp_Object val)
127 eassert (pdl->kind >= SPECPDL_LET);
128 pdl->let.old_value = val;
131 static Lisp_Object
132 specpdl_where (union specbinding *pdl)
134 eassert (pdl->kind > SPECPDL_LET);
135 return pdl->let.where;
138 static Lisp_Object
139 specpdl_arg (union specbinding *pdl)
141 eassert (pdl->kind == SPECPDL_UNWIND);
142 return pdl->unwind.arg;
145 Lisp_Object
146 backtrace_function (union specbinding *pdl)
148 eassert (pdl->kind == SPECPDL_BACKTRACE);
149 return pdl->bt.function;
152 static ptrdiff_t
153 backtrace_nargs (union specbinding *pdl)
155 eassert (pdl->kind == SPECPDL_BACKTRACE);
156 return pdl->bt.nargs;
159 Lisp_Object *
160 backtrace_args (union specbinding *pdl)
162 eassert (pdl->kind == SPECPDL_BACKTRACE);
163 return pdl->bt.args;
166 static bool
167 backtrace_debug_on_exit (union specbinding *pdl)
169 eassert (pdl->kind == SPECPDL_BACKTRACE);
170 return pdl->bt.debug_on_exit;
173 /* Functions to modify slots of backtrace records. */
175 static void
176 set_backtrace_args (union specbinding *pdl, Lisp_Object *args, ptrdiff_t nargs)
178 eassert (pdl->kind == SPECPDL_BACKTRACE);
179 pdl->bt.args = args;
180 pdl->bt.nargs = nargs;
183 static void
184 set_backtrace_debug_on_exit (union specbinding *pdl, bool doe)
186 eassert (pdl->kind == SPECPDL_BACKTRACE);
187 pdl->bt.debug_on_exit = doe;
190 /* Helper functions to scan the backtrace. */
192 bool
193 backtrace_p (union specbinding *pdl)
194 { return pdl >= specpdl; }
196 union specbinding *
197 backtrace_top (void)
199 union specbinding *pdl = specpdl_ptr - 1;
200 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
201 pdl--;
202 return pdl;
205 union specbinding *
206 backtrace_next (union specbinding *pdl)
208 pdl--;
209 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
210 pdl--;
211 return pdl;
215 void
216 init_eval_once (void)
218 enum { size = 50 };
219 union specbinding *pdlvec = xmalloc ((size + 1) * sizeof *specpdl);
220 specpdl_size = size;
221 specpdl = specpdl_ptr = pdlvec + 1;
222 /* Don't forget to update docs (lispref node "Local Variables"). */
223 max_specpdl_size = 1300; /* 1000 is not enough for CEDET's c-by.el. */
224 max_lisp_eval_depth = 600;
226 Vrun_hooks = Qnil;
229 static struct handler handlerlist_sentinel;
231 void
232 init_eval (void)
234 specpdl_ptr = specpdl;
235 { /* Put a dummy catcher at top-level so that handlerlist is never NULL.
236 This is important since handlerlist->nextfree holds the freelist
237 which would otherwise leak every time we unwind back to top-level. */
238 struct handler *c;
239 handlerlist = handlerlist_sentinel.nextfree = &handlerlist_sentinel;
240 PUSH_HANDLER (c, Qunbound, CATCHER);
241 eassert (c == &handlerlist_sentinel);
242 handlerlist_sentinel.nextfree = NULL;
243 handlerlist_sentinel.next = NULL;
245 Vquit_flag = Qnil;
246 debug_on_next_call = 0;
247 lisp_eval_depth = 0;
248 #ifdef DEBUG_GCPRO
249 gcpro_level = 0;
250 #endif
251 /* This is less than the initial value of num_nonmacro_input_events. */
252 when_entered_debugger = -1;
255 /* Unwind-protect function used by call_debugger. */
257 static void
258 restore_stack_limits (Lisp_Object data)
260 max_specpdl_size = XINT (XCAR (data));
261 max_lisp_eval_depth = XINT (XCDR (data));
264 static void grow_specpdl (void);
266 /* Call the Lisp debugger, giving it argument ARG. */
268 Lisp_Object
269 call_debugger (Lisp_Object arg)
271 bool debug_while_redisplaying;
272 ptrdiff_t count = SPECPDL_INDEX ();
273 Lisp_Object val;
274 EMACS_INT old_depth = max_lisp_eval_depth;
275 /* Do not allow max_specpdl_size less than actual depth (Bug#16603). */
276 EMACS_INT old_max = max (max_specpdl_size, count);
278 if (lisp_eval_depth + 40 > max_lisp_eval_depth)
279 max_lisp_eval_depth = lisp_eval_depth + 40;
281 /* While debugging Bug#16603, previous value of 100 was found
282 too small to avoid specpdl overflow in the debugger itself. */
283 if (max_specpdl_size - 200 < count)
284 max_specpdl_size = count + 200;
286 if (old_max == count)
288 /* We can enter the debugger due to specpdl overflow (Bug#16603). */
289 specpdl_ptr--;
290 grow_specpdl ();
293 /* Restore limits after leaving the debugger. */
294 record_unwind_protect (restore_stack_limits,
295 Fcons (make_number (old_max),
296 make_number (old_depth)));
298 #ifdef HAVE_WINDOW_SYSTEM
299 if (display_hourglass_p)
300 cancel_hourglass ();
301 #endif
303 debug_on_next_call = 0;
304 when_entered_debugger = num_nonmacro_input_events;
306 /* Resetting redisplaying_p to 0 makes sure that debug output is
307 displayed if the debugger is invoked during redisplay. */
308 debug_while_redisplaying = redisplaying_p;
309 redisplaying_p = 0;
310 specbind (intern ("debugger-may-continue"),
311 debug_while_redisplaying ? Qnil : Qt);
312 specbind (Qinhibit_redisplay, Qnil);
313 specbind (Qinhibit_debugger, Qt);
315 #if 0 /* Binding this prevents execution of Lisp code during
316 redisplay, which necessarily leads to display problems. */
317 specbind (Qinhibit_eval_during_redisplay, Qt);
318 #endif
320 val = apply1 (Vdebugger, arg);
322 /* Interrupting redisplay and resuming it later is not safe under
323 all circumstances. So, when the debugger returns, abort the
324 interrupted redisplay by going back to the top-level. */
325 if (debug_while_redisplaying)
326 Ftop_level ();
328 return unbind_to (count, val);
331 static void
332 do_debug_on_call (Lisp_Object code, ptrdiff_t count)
334 debug_on_next_call = 0;
335 set_backtrace_debug_on_exit (specpdl + count, true);
336 call_debugger (list1 (code));
339 /* NOTE!!! Every function that can call EVAL must protect its args
340 and temporaries from garbage collection while it needs them.
341 The definition of `For' shows what you have to do. */
343 DEFUN ("or", For, Sor, 0, UNEVALLED, 0,
344 doc: /* Eval args until one of them yields non-nil, then return that value.
345 The remaining args are not evalled at all.
346 If all args return nil, return nil.
347 usage: (or CONDITIONS...) */)
348 (Lisp_Object args)
350 register Lisp_Object val = Qnil;
351 struct gcpro gcpro1;
353 GCPRO1 (args);
355 while (CONSP (args))
357 val = eval_sub (XCAR (args));
358 if (!NILP (val))
359 break;
360 args = XCDR (args);
363 UNGCPRO;
364 return val;
367 DEFUN ("and", Fand, Sand, 0, UNEVALLED, 0,
368 doc: /* Eval args until one of them yields nil, then return nil.
369 The remaining args are not evalled at all.
370 If no arg yields nil, return the last arg's value.
371 usage: (and CONDITIONS...) */)
372 (Lisp_Object args)
374 register Lisp_Object val = Qt;
375 struct gcpro gcpro1;
377 GCPRO1 (args);
379 while (CONSP (args))
381 val = eval_sub (XCAR (args));
382 if (NILP (val))
383 break;
384 args = XCDR (args);
387 UNGCPRO;
388 return val;
391 DEFUN ("if", Fif, Sif, 2, UNEVALLED, 0,
392 doc: /* If COND yields non-nil, do THEN, else do ELSE...
393 Returns the value of THEN or the value of the last of the ELSE's.
394 THEN must be one expression, but ELSE... can be zero or more expressions.
395 If COND yields nil, and there are no ELSE's, the value is nil.
396 usage: (if COND THEN ELSE...) */)
397 (Lisp_Object args)
399 Lisp_Object cond;
400 struct gcpro gcpro1;
402 GCPRO1 (args);
403 cond = eval_sub (XCAR (args));
404 UNGCPRO;
406 if (!NILP (cond))
407 return eval_sub (Fcar (XCDR (args)));
408 return Fprogn (XCDR (XCDR (args)));
411 DEFUN ("cond", Fcond, Scond, 0, UNEVALLED, 0,
412 doc: /* Try each clause until one succeeds.
413 Each clause looks like (CONDITION BODY...). CONDITION is evaluated
414 and, if the value is non-nil, this clause succeeds:
415 then the expressions in BODY are evaluated and the last one's
416 value is the value of the cond-form.
417 If a clause has one element, as in (CONDITION), then the cond-form
418 returns CONDITION's value, if that is non-nil.
419 If no clause succeeds, cond returns nil.
420 usage: (cond CLAUSES...) */)
421 (Lisp_Object args)
423 Lisp_Object val = args;
424 struct gcpro gcpro1;
426 GCPRO1 (args);
427 while (CONSP (args))
429 Lisp_Object clause = XCAR (args);
430 val = eval_sub (Fcar (clause));
431 if (!NILP (val))
433 if (!NILP (XCDR (clause)))
434 val = Fprogn (XCDR (clause));
435 break;
437 args = XCDR (args);
439 UNGCPRO;
441 return val;
444 DEFUN ("progn", Fprogn, Sprogn, 0, UNEVALLED, 0,
445 doc: /* Eval BODY forms sequentially and return value of last one.
446 usage: (progn BODY...) */)
447 (Lisp_Object body)
449 Lisp_Object val = Qnil;
450 struct gcpro gcpro1;
452 GCPRO1 (body);
454 while (CONSP (body))
456 val = eval_sub (XCAR (body));
457 body = XCDR (body);
460 UNGCPRO;
461 return val;
464 /* Evaluate BODY sequentially, discarding its value. Suitable for
465 record_unwind_protect. */
467 void
468 unwind_body (Lisp_Object body)
470 Fprogn (body);
473 DEFUN ("prog1", Fprog1, Sprog1, 1, UNEVALLED, 0,
474 doc: /* Eval FIRST and BODY sequentially; return value from FIRST.
475 The value of FIRST is saved during the evaluation of the remaining args,
476 whose values are discarded.
477 usage: (prog1 FIRST BODY...) */)
478 (Lisp_Object args)
480 Lisp_Object val;
481 Lisp_Object args_left;
482 struct gcpro gcpro1, gcpro2;
484 args_left = args;
485 val = args;
486 GCPRO2 (args, val);
488 val = eval_sub (XCAR (args_left));
489 while (CONSP (args_left = XCDR (args_left)))
490 eval_sub (XCAR (args_left));
492 UNGCPRO;
493 return val;
496 DEFUN ("prog2", Fprog2, Sprog2, 2, UNEVALLED, 0,
497 doc: /* Eval FORM1, FORM2 and BODY sequentially; return value from FORM2.
498 The value of FORM2 is saved during the evaluation of the
499 remaining args, whose values are discarded.
500 usage: (prog2 FORM1 FORM2 BODY...) */)
501 (Lisp_Object args)
503 struct gcpro gcpro1;
505 GCPRO1 (args);
506 eval_sub (XCAR (args));
507 UNGCPRO;
508 return Fprog1 (XCDR (args));
511 DEFUN ("setq", Fsetq, Ssetq, 0, UNEVALLED, 0,
512 doc: /* Set each SYM to the value of its VAL.
513 The symbols SYM are variables; they are literal (not evaluated).
514 The values VAL are expressions; they are evaluated.
515 Thus, (setq x (1+ y)) sets `x' to the value of `(1+ y)'.
516 The second VAL is not computed until after the first SYM is set, and so on;
517 each VAL can use the new value of variables set earlier in the `setq'.
518 The return value of the `setq' form is the value of the last VAL.
519 usage: (setq [SYM VAL]...) */)
520 (Lisp_Object args)
522 Lisp_Object val, sym, lex_binding;
524 val = args;
525 if (CONSP (args))
527 Lisp_Object args_left = args;
528 struct gcpro gcpro1;
529 GCPRO1 (args);
533 val = eval_sub (Fcar (XCDR (args_left)));
534 sym = XCAR (args_left);
536 /* Like for eval_sub, we do not check declared_special here since
537 it's been done when let-binding. */
538 if (!NILP (Vinternal_interpreter_environment) /* Mere optimization! */
539 && SYMBOLP (sym)
540 && !NILP (lex_binding
541 = Fassq (sym, Vinternal_interpreter_environment)))
542 XSETCDR (lex_binding, val); /* SYM is lexically bound. */
543 else
544 Fset (sym, val); /* SYM is dynamically bound. */
546 args_left = Fcdr (XCDR (args_left));
548 while (CONSP (args_left));
550 UNGCPRO;
553 return val;
556 DEFUN ("quote", Fquote, Squote, 1, UNEVALLED, 0,
557 doc: /* Return the argument, without evaluating it. `(quote x)' yields `x'.
558 Warning: `quote' does not construct its return value, but just returns
559 the value that was pre-constructed by the Lisp reader (see info node
560 `(elisp)Printed Representation').
561 This means that '(a . b) is not identical to (cons 'a 'b): the former
562 does not cons. Quoting should be reserved for constants that will
563 never be modified by side-effects, unless you like self-modifying code.
564 See the common pitfall in info node `(elisp)Rearrangement' for an example
565 of unexpected results when a quoted object is modified.
566 usage: (quote ARG) */)
567 (Lisp_Object args)
569 if (CONSP (XCDR (args)))
570 xsignal2 (Qwrong_number_of_arguments, Qquote, Flength (args));
571 return XCAR (args);
574 DEFUN ("function", Ffunction, Sfunction, 1, UNEVALLED, 0,
575 doc: /* Like `quote', but preferred for objects which are functions.
576 In byte compilation, `function' causes its argument to be compiled.
577 `quote' cannot do that.
578 usage: (function ARG) */)
579 (Lisp_Object args)
581 Lisp_Object quoted = XCAR (args);
583 if (CONSP (XCDR (args)))
584 xsignal2 (Qwrong_number_of_arguments, Qfunction, Flength (args));
586 if (!NILP (Vinternal_interpreter_environment)
587 && CONSP (quoted)
588 && EQ (XCAR (quoted), Qlambda))
589 /* This is a lambda expression within a lexical environment;
590 return an interpreted closure instead of a simple lambda. */
591 return Fcons (Qclosure, Fcons (Vinternal_interpreter_environment,
592 XCDR (quoted)));
593 else
594 /* Simply quote the argument. */
595 return quoted;
599 DEFUN ("defvaralias", Fdefvaralias, Sdefvaralias, 2, 3, 0,
600 doc: /* Make NEW-ALIAS a variable alias for symbol BASE-VARIABLE.
601 Aliased variables always have the same value; setting one sets the other.
602 Third arg DOCSTRING, if non-nil, is documentation for NEW-ALIAS. If it is
603 omitted or nil, NEW-ALIAS gets the documentation string of BASE-VARIABLE,
604 or of the variable at the end of the chain of aliases, if BASE-VARIABLE is
605 itself an alias. If NEW-ALIAS is bound, and BASE-VARIABLE is not,
606 then the value of BASE-VARIABLE is set to that of NEW-ALIAS.
607 The return value is BASE-VARIABLE. */)
608 (Lisp_Object new_alias, Lisp_Object base_variable, Lisp_Object docstring)
610 struct Lisp_Symbol *sym;
612 CHECK_SYMBOL (new_alias);
613 CHECK_SYMBOL (base_variable);
615 sym = XSYMBOL (new_alias);
617 if (sym->constant)
618 /* Not sure why, but why not? */
619 error ("Cannot make a constant an alias");
621 switch (sym->redirect)
623 case SYMBOL_FORWARDED:
624 error ("Cannot make an internal variable an alias");
625 case SYMBOL_LOCALIZED:
626 error ("Don't know how to make a localized variable an alias");
629 /* http://lists.gnu.org/archive/html/emacs-devel/2008-04/msg00834.html
630 If n_a is bound, but b_v is not, set the value of b_v to n_a,
631 so that old-code that affects n_a before the aliasing is setup
632 still works. */
633 if (NILP (Fboundp (base_variable)))
634 set_internal (base_variable, find_symbol_value (new_alias), Qnil, 1);
637 union specbinding *p;
639 for (p = specpdl_ptr; p > specpdl; )
640 if ((--p)->kind >= SPECPDL_LET
641 && (EQ (new_alias, specpdl_symbol (p))))
642 error ("Don't know how to make a let-bound variable an alias");
645 sym->declared_special = 1;
646 XSYMBOL (base_variable)->declared_special = 1;
647 sym->redirect = SYMBOL_VARALIAS;
648 SET_SYMBOL_ALIAS (sym, XSYMBOL (base_variable));
649 sym->constant = SYMBOL_CONSTANT_P (base_variable);
650 LOADHIST_ATTACH (new_alias);
651 /* Even if docstring is nil: remove old docstring. */
652 Fput (new_alias, Qvariable_documentation, docstring);
654 return base_variable;
657 static union specbinding *
658 default_toplevel_binding (Lisp_Object symbol)
660 union specbinding *binding = NULL;
661 union specbinding *pdl = specpdl_ptr;
662 while (pdl > specpdl)
664 switch ((--pdl)->kind)
666 case SPECPDL_LET_DEFAULT:
667 case SPECPDL_LET:
668 if (EQ (specpdl_symbol (pdl), symbol))
669 binding = pdl;
670 break;
673 return binding;
676 DEFUN ("default-toplevel-value", Fdefault_toplevel_value, Sdefault_toplevel_value, 1, 1, 0,
677 doc: /* Return SYMBOL's toplevel default value.
678 "Toplevel" means outside of any let binding. */)
679 (Lisp_Object symbol)
681 union specbinding *binding = default_toplevel_binding (symbol);
682 Lisp_Object value
683 = binding ? specpdl_old_value (binding) : Fdefault_value (symbol);
684 if (!EQ (value, Qunbound))
685 return value;
686 xsignal1 (Qvoid_variable, symbol);
689 DEFUN ("set-default-toplevel-value", Fset_default_toplevel_value,
690 Sset_default_toplevel_value, 2, 2, 0,
691 doc: /* Set SYMBOL's toplevel default value to VALUE.
692 "Toplevel" means outside of any let binding. */)
693 (Lisp_Object symbol, Lisp_Object value)
695 union specbinding *binding = default_toplevel_binding (symbol);
696 if (binding)
697 set_specpdl_old_value (binding, value);
698 else
699 Fset_default (symbol, value);
700 return Qnil;
703 DEFUN ("defvar", Fdefvar, Sdefvar, 1, UNEVALLED, 0,
704 doc: /* Define SYMBOL as a variable, and return SYMBOL.
705 You are not required to define a variable in order to use it, but
706 defining it lets you supply an initial value and documentation, which
707 can be referred to by the Emacs help facilities and other programming
708 tools. The `defvar' form also declares the variable as \"special\",
709 so that it is always dynamically bound even if `lexical-binding' is t.
711 The optional argument INITVALUE is evaluated, and used to set SYMBOL,
712 only if SYMBOL's value is void. If SYMBOL is buffer-local, its
713 default value is what is set; buffer-local values are not affected.
714 If INITVALUE is missing, SYMBOL's value is not set.
716 If SYMBOL has a local binding, then this form affects the local
717 binding. This is usually not what you want. Thus, if you need to
718 load a file defining variables, with this form or with `defconst' or
719 `defcustom', you should always load that file _outside_ any bindings
720 for these variables. \(`defconst' and `defcustom' behave similarly in
721 this respect.)
723 The optional argument DOCSTRING is a documentation string for the
724 variable.
726 To define a user option, use `defcustom' instead of `defvar'.
727 usage: (defvar SYMBOL &optional INITVALUE DOCSTRING) */)
728 (Lisp_Object args)
730 Lisp_Object sym, tem, tail;
732 sym = XCAR (args);
733 tail = XCDR (args);
735 if (CONSP (tail))
737 if (CONSP (XCDR (tail)) && CONSP (XCDR (XCDR (tail))))
738 error ("Too many arguments");
740 tem = Fdefault_boundp (sym);
742 /* Do it before evaluating the initial value, for self-references. */
743 XSYMBOL (sym)->declared_special = 1;
745 if (NILP (tem))
746 Fset_default (sym, eval_sub (XCAR (tail)));
747 else
748 { /* Check if there is really a global binding rather than just a let
749 binding that shadows the global unboundness of the var. */
750 union specbinding *binding = default_toplevel_binding (sym);
751 if (binding && EQ (specpdl_old_value (binding), Qunbound))
753 set_specpdl_old_value (binding, eval_sub (XCAR (tail)));
756 tail = XCDR (tail);
757 tem = Fcar (tail);
758 if (!NILP (tem))
760 if (!NILP (Vpurify_flag))
761 tem = Fpurecopy (tem);
762 Fput (sym, Qvariable_documentation, tem);
764 LOADHIST_ATTACH (sym);
766 else if (!NILP (Vinternal_interpreter_environment)
767 && !XSYMBOL (sym)->declared_special)
768 /* A simple (defvar foo) with lexical scoping does "nothing" except
769 declare that var to be dynamically scoped *locally* (i.e. within
770 the current file or let-block). */
771 Vinternal_interpreter_environment
772 = Fcons (sym, Vinternal_interpreter_environment);
773 else
775 /* Simple (defvar <var>) should not count as a definition at all.
776 It could get in the way of other definitions, and unloading this
777 package could try to make the variable unbound. */
780 return sym;
783 DEFUN ("defconst", Fdefconst, Sdefconst, 2, UNEVALLED, 0,
784 doc: /* Define SYMBOL as a constant variable.
785 This declares that neither programs nor users should ever change the
786 value. This constancy is not actually enforced by Emacs Lisp, but
787 SYMBOL is marked as a special variable so that it is never lexically
788 bound.
790 The `defconst' form always sets the value of SYMBOL to the result of
791 evalling INITVALUE. If SYMBOL is buffer-local, its default value is
792 what is set; buffer-local values are not affected. If SYMBOL has a
793 local binding, then this form sets the local binding's value.
794 However, you should normally not make local bindings for variables
795 defined with this form.
797 The optional DOCSTRING specifies the variable's documentation string.
798 usage: (defconst SYMBOL INITVALUE [DOCSTRING]) */)
799 (Lisp_Object args)
801 Lisp_Object sym, tem;
803 sym = XCAR (args);
804 if (CONSP (Fcdr (XCDR (XCDR (args)))))
805 error ("Too many arguments");
807 tem = eval_sub (Fcar (XCDR (args)));
808 if (!NILP (Vpurify_flag))
809 tem = Fpurecopy (tem);
810 Fset_default (sym, tem);
811 XSYMBOL (sym)->declared_special = 1;
812 tem = Fcar (XCDR (XCDR (args)));
813 if (!NILP (tem))
815 if (!NILP (Vpurify_flag))
816 tem = Fpurecopy (tem);
817 Fput (sym, Qvariable_documentation, tem);
819 Fput (sym, Qrisky_local_variable, Qt);
820 LOADHIST_ATTACH (sym);
821 return sym;
824 /* Make SYMBOL lexically scoped. */
825 DEFUN ("internal-make-var-non-special", Fmake_var_non_special,
826 Smake_var_non_special, 1, 1, 0,
827 doc: /* Internal function. */)
828 (Lisp_Object symbol)
830 CHECK_SYMBOL (symbol);
831 XSYMBOL (symbol)->declared_special = 0;
832 return Qnil;
836 DEFUN ("let*", FletX, SletX, 1, UNEVALLED, 0,
837 doc: /* Bind variables according to VARLIST then eval BODY.
838 The value of the last form in BODY is returned.
839 Each element of VARLIST is a symbol (which is bound to nil)
840 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
841 Each VALUEFORM can refer to the symbols already bound by this VARLIST.
842 usage: (let* VARLIST BODY...) */)
843 (Lisp_Object args)
845 Lisp_Object varlist, var, val, elt, lexenv;
846 ptrdiff_t count = SPECPDL_INDEX ();
847 struct gcpro gcpro1, gcpro2, gcpro3;
849 GCPRO3 (args, elt, varlist);
851 lexenv = Vinternal_interpreter_environment;
853 varlist = XCAR (args);
854 while (CONSP (varlist))
856 QUIT;
858 elt = XCAR (varlist);
859 if (SYMBOLP (elt))
861 var = elt;
862 val = Qnil;
864 else if (! NILP (Fcdr (Fcdr (elt))))
865 signal_error ("`let' bindings can have only one value-form", elt);
866 else
868 var = Fcar (elt);
869 val = eval_sub (Fcar (Fcdr (elt)));
872 if (!NILP (lexenv) && SYMBOLP (var)
873 && !XSYMBOL (var)->declared_special
874 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
875 /* Lexically bind VAR by adding it to the interpreter's binding
876 alist. */
878 Lisp_Object newenv
879 = Fcons (Fcons (var, val), Vinternal_interpreter_environment);
880 if (EQ (Vinternal_interpreter_environment, lexenv))
881 /* Save the old lexical environment on the specpdl stack,
882 but only for the first lexical binding, since we'll never
883 need to revert to one of the intermediate ones. */
884 specbind (Qinternal_interpreter_environment, newenv);
885 else
886 Vinternal_interpreter_environment = newenv;
888 else
889 specbind (var, val);
891 varlist = XCDR (varlist);
893 UNGCPRO;
894 val = Fprogn (XCDR (args));
895 return unbind_to (count, val);
898 DEFUN ("let", Flet, Slet, 1, UNEVALLED, 0,
899 doc: /* Bind variables according to VARLIST then eval BODY.
900 The value of the last form in BODY is returned.
901 Each element of VARLIST is a symbol (which is bound to nil)
902 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
903 All the VALUEFORMs are evalled before any symbols are bound.
904 usage: (let VARLIST BODY...) */)
905 (Lisp_Object args)
907 Lisp_Object *temps, tem, lexenv;
908 register Lisp_Object elt, varlist;
909 ptrdiff_t count = SPECPDL_INDEX ();
910 ptrdiff_t argnum;
911 struct gcpro gcpro1, gcpro2;
912 USE_SAFE_ALLOCA;
914 varlist = XCAR (args);
916 /* Make space to hold the values to give the bound variables. */
917 elt = Flength (varlist);
918 SAFE_ALLOCA_LISP (temps, XFASTINT (elt));
920 /* Compute the values and store them in `temps'. */
922 GCPRO2 (args, *temps);
923 gcpro2.nvars = 0;
925 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
927 QUIT;
928 elt = XCAR (varlist);
929 if (SYMBOLP (elt))
930 temps [argnum++] = Qnil;
931 else if (! NILP (Fcdr (Fcdr (elt))))
932 signal_error ("`let' bindings can have only one value-form", elt);
933 else
934 temps [argnum++] = eval_sub (Fcar (Fcdr (elt)));
935 gcpro2.nvars = argnum;
937 UNGCPRO;
939 lexenv = Vinternal_interpreter_environment;
941 varlist = XCAR (args);
942 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
944 Lisp_Object var;
946 elt = XCAR (varlist);
947 var = SYMBOLP (elt) ? elt : Fcar (elt);
948 tem = temps[argnum++];
950 if (!NILP (lexenv) && SYMBOLP (var)
951 && !XSYMBOL (var)->declared_special
952 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
953 /* Lexically bind VAR by adding it to the lexenv alist. */
954 lexenv = Fcons (Fcons (var, tem), lexenv);
955 else
956 /* Dynamically bind VAR. */
957 specbind (var, tem);
960 if (!EQ (lexenv, Vinternal_interpreter_environment))
961 /* Instantiate a new lexical environment. */
962 specbind (Qinternal_interpreter_environment, lexenv);
964 elt = Fprogn (XCDR (args));
965 SAFE_FREE ();
966 return unbind_to (count, elt);
969 DEFUN ("while", Fwhile, Swhile, 1, UNEVALLED, 0,
970 doc: /* If TEST yields non-nil, eval BODY... and repeat.
971 The order of execution is thus TEST, BODY, TEST, BODY and so on
972 until TEST returns nil.
973 usage: (while TEST BODY...) */)
974 (Lisp_Object args)
976 Lisp_Object test, body;
977 struct gcpro gcpro1, gcpro2;
979 GCPRO2 (test, body);
981 test = XCAR (args);
982 body = XCDR (args);
983 while (!NILP (eval_sub (test)))
985 QUIT;
986 Fprogn (body);
989 UNGCPRO;
990 return Qnil;
993 DEFUN ("macroexpand", Fmacroexpand, Smacroexpand, 1, 2, 0,
994 doc: /* Return result of expanding macros at top level of FORM.
995 If FORM is not a macro call, it is returned unchanged.
996 Otherwise, the macro is expanded and the expansion is considered
997 in place of FORM. When a non-macro-call results, it is returned.
999 The second optional arg ENVIRONMENT specifies an environment of macro
1000 definitions to shadow the loaded ones for use in file byte-compilation. */)
1001 (Lisp_Object form, Lisp_Object environment)
1003 /* With cleanups from Hallvard Furuseth. */
1004 register Lisp_Object expander, sym, def, tem;
1006 while (1)
1008 /* Come back here each time we expand a macro call,
1009 in case it expands into another macro call. */
1010 if (!CONSP (form))
1011 break;
1012 /* Set SYM, give DEF and TEM right values in case SYM is not a symbol. */
1013 def = sym = XCAR (form);
1014 tem = Qnil;
1015 /* Trace symbols aliases to other symbols
1016 until we get a symbol that is not an alias. */
1017 while (SYMBOLP (def))
1019 QUIT;
1020 sym = def;
1021 tem = Fassq (sym, environment);
1022 if (NILP (tem))
1024 def = XSYMBOL (sym)->function;
1025 if (!NILP (def))
1026 continue;
1028 break;
1030 /* Right now TEM is the result from SYM in ENVIRONMENT,
1031 and if TEM is nil then DEF is SYM's function definition. */
1032 if (NILP (tem))
1034 /* SYM is not mentioned in ENVIRONMENT.
1035 Look at its function definition. */
1036 struct gcpro gcpro1;
1037 GCPRO1 (form);
1038 def = Fautoload_do_load (def, sym, Qmacro);
1039 UNGCPRO;
1040 if (!CONSP (def))
1041 /* Not defined or definition not suitable. */
1042 break;
1043 if (!EQ (XCAR (def), Qmacro))
1044 break;
1045 else expander = XCDR (def);
1047 else
1049 expander = XCDR (tem);
1050 if (NILP (expander))
1051 break;
1054 Lisp_Object newform = apply1 (expander, XCDR (form));
1055 if (EQ (form, newform))
1056 break;
1057 else
1058 form = newform;
1061 return form;
1064 DEFUN ("catch", Fcatch, Scatch, 1, UNEVALLED, 0,
1065 doc: /* Eval BODY allowing nonlocal exits using `throw'.
1066 TAG is evalled to get the tag to use; it must not be nil.
1068 Then the BODY is executed.
1069 Within BODY, a call to `throw' with the same TAG exits BODY and this `catch'.
1070 If no throw happens, `catch' returns the value of the last BODY form.
1071 If a throw happens, it specifies the value to return from `catch'.
1072 usage: (catch TAG BODY...) */)
1073 (Lisp_Object args)
1075 register Lisp_Object tag;
1076 struct gcpro gcpro1;
1078 GCPRO1 (args);
1079 tag = eval_sub (XCAR (args));
1080 UNGCPRO;
1081 return internal_catch (tag, Fprogn, XCDR (args));
1084 /* Assert that E is true, as a comment only. Use this instead of
1085 eassert (E) when E contains variables that might be clobbered by a
1086 longjmp. */
1088 #define clobbered_eassert(E) ((void) 0)
1090 /* Set up a catch, then call C function FUNC on argument ARG.
1091 FUNC should return a Lisp_Object.
1092 This is how catches are done from within C code. */
1094 Lisp_Object
1095 internal_catch (Lisp_Object tag, Lisp_Object (*func) (Lisp_Object), Lisp_Object arg)
1097 /* This structure is made part of the chain `catchlist'. */
1098 struct handler *c;
1100 /* Fill in the components of c, and put it on the list. */
1101 PUSH_HANDLER (c, tag, CATCHER);
1103 /* Call FUNC. */
1104 if (! sys_setjmp (c->jmp))
1106 Lisp_Object val = (*func) (arg);
1107 clobbered_eassert (handlerlist == c);
1108 handlerlist = handlerlist->next;
1109 return val;
1111 else
1112 { /* Throw works by a longjmp that comes right here. */
1113 Lisp_Object val = handlerlist->val;
1114 clobbered_eassert (handlerlist == c);
1115 handlerlist = handlerlist->next;
1116 return val;
1120 /* Unwind the specbind, catch, and handler stacks back to CATCH, and
1121 jump to that CATCH, returning VALUE as the value of that catch.
1123 This is the guts of Fthrow and Fsignal; they differ only in the way
1124 they choose the catch tag to throw to. A catch tag for a
1125 condition-case form has a TAG of Qnil.
1127 Before each catch is discarded, unbind all special bindings and
1128 execute all unwind-protect clauses made above that catch. Unwind
1129 the handler stack as we go, so that the proper handlers are in
1130 effect for each unwind-protect clause we run. At the end, restore
1131 some static info saved in CATCH, and longjmp to the location
1132 specified there.
1134 This is used for correct unwinding in Fthrow and Fsignal. */
1136 static _Noreturn void
1137 unwind_to_catch (struct handler *catch, Lisp_Object value)
1139 bool last_time;
1141 eassert (catch->next);
1143 /* Save the value in the tag. */
1144 catch->val = value;
1146 /* Restore certain special C variables. */
1147 set_poll_suppress_count (catch->poll_suppress_count);
1148 unblock_input_to (catch->interrupt_input_blocked);
1149 immediate_quit = 0;
1153 /* Unwind the specpdl stack, and then restore the proper set of
1154 handlers. */
1155 unbind_to (handlerlist->pdlcount, Qnil);
1156 last_time = handlerlist == catch;
1157 if (! last_time)
1158 handlerlist = handlerlist->next;
1160 while (! last_time);
1162 eassert (handlerlist == catch);
1164 byte_stack_list = catch->byte_stack;
1165 gcprolist = catch->gcpro;
1166 #ifdef DEBUG_GCPRO
1167 gcpro_level = gcprolist ? gcprolist->level + 1 : 0;
1168 #endif
1169 lisp_eval_depth = catch->lisp_eval_depth;
1171 sys_longjmp (catch->jmp, 1);
1174 DEFUN ("throw", Fthrow, Sthrow, 2, 2, 0,
1175 doc: /* Throw to the catch for TAG and return VALUE from it.
1176 Both TAG and VALUE are evalled. */)
1177 (register Lisp_Object tag, Lisp_Object value)
1179 struct handler *c;
1181 if (!NILP (tag))
1182 for (c = handlerlist; c; c = c->next)
1184 if (c->type == CATCHER && EQ (c->tag_or_ch, tag))
1185 unwind_to_catch (c, value);
1187 xsignal2 (Qno_catch, tag, value);
1191 DEFUN ("unwind-protect", Funwind_protect, Sunwind_protect, 1, UNEVALLED, 0,
1192 doc: /* Do BODYFORM, protecting with UNWINDFORMS.
1193 If BODYFORM completes normally, its value is returned
1194 after executing the UNWINDFORMS.
1195 If BODYFORM exits nonlocally, the UNWINDFORMS are executed anyway.
1196 usage: (unwind-protect BODYFORM UNWINDFORMS...) */)
1197 (Lisp_Object args)
1199 Lisp_Object val;
1200 ptrdiff_t count = SPECPDL_INDEX ();
1202 record_unwind_protect (unwind_body, XCDR (args));
1203 val = eval_sub (XCAR (args));
1204 return unbind_to (count, val);
1207 DEFUN ("condition-case", Fcondition_case, Scondition_case, 2, UNEVALLED, 0,
1208 doc: /* Regain control when an error is signaled.
1209 Executes BODYFORM and returns its value if no error happens.
1210 Each element of HANDLERS looks like (CONDITION-NAME BODY...)
1211 where the BODY is made of Lisp expressions.
1213 A handler is applicable to an error
1214 if CONDITION-NAME is one of the error's condition names.
1215 If an error happens, the first applicable handler is run.
1217 The car of a handler may be a list of condition names instead of a
1218 single condition name; then it handles all of them. If the special
1219 condition name `debug' is present in this list, it allows another
1220 condition in the list to run the debugger if `debug-on-error' and the
1221 other usual mechanisms says it should (otherwise, `condition-case'
1222 suppresses the debugger).
1224 When a handler handles an error, control returns to the `condition-case'
1225 and it executes the handler's BODY...
1226 with VAR bound to (ERROR-SYMBOL . SIGNAL-DATA) from the error.
1227 \(If VAR is nil, the handler can't access that information.)
1228 Then the value of the last BODY form is returned from the `condition-case'
1229 expression.
1231 See also the function `signal' for more info.
1232 usage: (condition-case VAR BODYFORM &rest HANDLERS) */)
1233 (Lisp_Object args)
1235 Lisp_Object var = XCAR (args);
1236 Lisp_Object bodyform = XCAR (XCDR (args));
1237 Lisp_Object handlers = XCDR (XCDR (args));
1239 return internal_lisp_condition_case (var, bodyform, handlers);
1242 /* Like Fcondition_case, but the args are separate
1243 rather than passed in a list. Used by Fbyte_code. */
1245 Lisp_Object
1246 internal_lisp_condition_case (volatile Lisp_Object var, Lisp_Object bodyform,
1247 Lisp_Object handlers)
1249 Lisp_Object val;
1250 struct handler *c;
1251 struct handler *oldhandlerlist = handlerlist;
1252 int clausenb = 0;
1254 CHECK_SYMBOL (var);
1256 for (val = handlers; CONSP (val); val = XCDR (val))
1258 Lisp_Object tem = XCAR (val);
1259 clausenb++;
1260 if (! (NILP (tem)
1261 || (CONSP (tem)
1262 && (SYMBOLP (XCAR (tem))
1263 || CONSP (XCAR (tem))))))
1264 error ("Invalid condition handler: %s",
1265 SDATA (Fprin1_to_string (tem, Qt)));
1268 { /* The first clause is the one that should be checked first, so it should
1269 be added to handlerlist last. So we build in `clauses' a table that
1270 contains `handlers' but in reverse order. SAFE_ALLOCA won't work
1271 here due to the setjmp, so impose a MAX_ALLOCA limit. */
1272 if (MAX_ALLOCA / word_size < clausenb)
1273 memory_full (SIZE_MAX);
1274 Lisp_Object *clauses = alloca (clausenb * sizeof *clauses);
1275 Lisp_Object *volatile clauses_volatile = clauses;
1276 int i = clausenb;
1277 for (val = handlers; CONSP (val); val = XCDR (val))
1278 clauses[--i] = XCAR (val);
1279 for (i = 0; i < clausenb; i++)
1281 Lisp_Object clause = clauses[i];
1282 Lisp_Object condition = XCAR (clause);
1283 if (!CONSP (condition))
1284 condition = Fcons (condition, Qnil);
1285 PUSH_HANDLER (c, condition, CONDITION_CASE);
1286 if (sys_setjmp (c->jmp))
1288 ptrdiff_t count = SPECPDL_INDEX ();
1289 Lisp_Object val = handlerlist->val;
1290 Lisp_Object *chosen_clause = clauses_volatile;
1291 for (c = handlerlist->next; c != oldhandlerlist; c = c->next)
1292 chosen_clause++;
1293 handlerlist = oldhandlerlist;
1294 if (!NILP (var))
1296 if (!NILP (Vinternal_interpreter_environment))
1297 specbind (Qinternal_interpreter_environment,
1298 Fcons (Fcons (var, val),
1299 Vinternal_interpreter_environment));
1300 else
1301 specbind (var, val);
1303 val = Fprogn (XCDR (*chosen_clause));
1304 /* Note that this just undoes the binding of var; whoever
1305 longjumped to us unwound the stack to c.pdlcount before
1306 throwing. */
1307 if (!NILP (var))
1308 unbind_to (count, Qnil);
1309 return val;
1314 val = eval_sub (bodyform);
1315 handlerlist = oldhandlerlist;
1316 return val;
1319 /* Call the function BFUN with no arguments, catching errors within it
1320 according to HANDLERS. If there is an error, call HFUN with
1321 one argument which is the data that describes the error:
1322 (SIGNALNAME . DATA)
1324 HANDLERS can be a list of conditions to catch.
1325 If HANDLERS is Qt, catch all errors.
1326 If HANDLERS is Qerror, catch all errors
1327 but allow the debugger to run if that is enabled. */
1329 Lisp_Object
1330 internal_condition_case (Lisp_Object (*bfun) (void), Lisp_Object handlers,
1331 Lisp_Object (*hfun) (Lisp_Object))
1333 Lisp_Object val;
1334 struct handler *c;
1336 PUSH_HANDLER (c, handlers, CONDITION_CASE);
1337 if (sys_setjmp (c->jmp))
1339 Lisp_Object val = handlerlist->val;
1340 clobbered_eassert (handlerlist == c);
1341 handlerlist = handlerlist->next;
1342 return (*hfun) (val);
1345 val = (*bfun) ();
1346 clobbered_eassert (handlerlist == c);
1347 handlerlist = handlerlist->next;
1348 return val;
1351 /* Like internal_condition_case but call BFUN with ARG as its argument. */
1353 Lisp_Object
1354 internal_condition_case_1 (Lisp_Object (*bfun) (Lisp_Object), Lisp_Object arg,
1355 Lisp_Object handlers, Lisp_Object (*hfun) (Lisp_Object))
1357 Lisp_Object val;
1358 struct handler *c;
1360 PUSH_HANDLER (c, handlers, CONDITION_CASE);
1361 if (sys_setjmp (c->jmp))
1363 Lisp_Object val = handlerlist->val;
1364 clobbered_eassert (handlerlist == c);
1365 handlerlist = handlerlist->next;
1366 return (*hfun) (val);
1369 val = (*bfun) (arg);
1370 clobbered_eassert (handlerlist == c);
1371 handlerlist = handlerlist->next;
1372 return val;
1375 /* Like internal_condition_case_1 but call BFUN with ARG1 and ARG2 as
1376 its arguments. */
1378 Lisp_Object
1379 internal_condition_case_2 (Lisp_Object (*bfun) (Lisp_Object, Lisp_Object),
1380 Lisp_Object arg1,
1381 Lisp_Object arg2,
1382 Lisp_Object handlers,
1383 Lisp_Object (*hfun) (Lisp_Object))
1385 Lisp_Object val;
1386 struct handler *c;
1388 PUSH_HANDLER (c, handlers, CONDITION_CASE);
1389 if (sys_setjmp (c->jmp))
1391 Lisp_Object val = handlerlist->val;
1392 clobbered_eassert (handlerlist == c);
1393 handlerlist = handlerlist->next;
1394 return (*hfun) (val);
1397 val = (*bfun) (arg1, arg2);
1398 clobbered_eassert (handlerlist == c);
1399 handlerlist = handlerlist->next;
1400 return val;
1403 /* Like internal_condition_case but call BFUN with NARGS as first,
1404 and ARGS as second argument. */
1406 Lisp_Object
1407 internal_condition_case_n (Lisp_Object (*bfun) (ptrdiff_t, Lisp_Object *),
1408 ptrdiff_t nargs,
1409 Lisp_Object *args,
1410 Lisp_Object handlers,
1411 Lisp_Object (*hfun) (Lisp_Object err,
1412 ptrdiff_t nargs,
1413 Lisp_Object *args))
1415 Lisp_Object val;
1416 struct handler *c;
1418 PUSH_HANDLER (c, handlers, CONDITION_CASE);
1419 if (sys_setjmp (c->jmp))
1421 Lisp_Object val = handlerlist->val;
1422 clobbered_eassert (handlerlist == c);
1423 handlerlist = handlerlist->next;
1424 return (*hfun) (val, nargs, args);
1427 val = (*bfun) (nargs, args);
1428 clobbered_eassert (handlerlist == c);
1429 handlerlist = handlerlist->next;
1430 return val;
1434 static Lisp_Object find_handler_clause (Lisp_Object, Lisp_Object);
1435 static bool maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig,
1436 Lisp_Object data);
1438 void
1439 process_quit_flag (void)
1441 Lisp_Object flag = Vquit_flag;
1442 Vquit_flag = Qnil;
1443 if (EQ (flag, Qkill_emacs))
1444 Fkill_emacs (Qnil);
1445 if (EQ (Vthrow_on_input, flag))
1446 Fthrow (Vthrow_on_input, Qt);
1447 Fsignal (Qquit, Qnil);
1450 DEFUN ("signal", Fsignal, Ssignal, 2, 2, 0,
1451 doc: /* Signal an error. Args are ERROR-SYMBOL and associated DATA.
1452 This function does not return.
1454 An error symbol is a symbol with an `error-conditions' property
1455 that is a list of condition names.
1456 A handler for any of those names will get to handle this signal.
1457 The symbol `error' should normally be one of them.
1459 DATA should be a list. Its elements are printed as part of the error message.
1460 See Info anchor `(elisp)Definition of signal' for some details on how this
1461 error message is constructed.
1462 If the signal is handled, DATA is made available to the handler.
1463 See also the function `condition-case'. */)
1464 (Lisp_Object error_symbol, Lisp_Object data)
1466 /* When memory is full, ERROR-SYMBOL is nil,
1467 and DATA is (REAL-ERROR-SYMBOL . REAL-DATA).
1468 That is a special case--don't do this in other situations. */
1469 Lisp_Object conditions;
1470 Lisp_Object string;
1471 Lisp_Object real_error_symbol
1472 = (NILP (error_symbol) ? Fcar (data) : error_symbol);
1473 register Lisp_Object clause = Qnil;
1474 struct handler *h;
1476 immediate_quit = 0;
1477 abort_on_gc = 0;
1478 if (gc_in_progress || waiting_for_input)
1479 emacs_abort ();
1481 #if 0 /* rms: I don't know why this was here,
1482 but it is surely wrong for an error that is handled. */
1483 #ifdef HAVE_WINDOW_SYSTEM
1484 if (display_hourglass_p)
1485 cancel_hourglass ();
1486 #endif
1487 #endif
1489 /* This hook is used by edebug. */
1490 if (! NILP (Vsignal_hook_function)
1491 && ! NILP (error_symbol))
1493 /* Edebug takes care of restoring these variables when it exits. */
1494 if (lisp_eval_depth + 20 > max_lisp_eval_depth)
1495 max_lisp_eval_depth = lisp_eval_depth + 20;
1497 if (SPECPDL_INDEX () + 40 > max_specpdl_size)
1498 max_specpdl_size = SPECPDL_INDEX () + 40;
1500 call2 (Vsignal_hook_function, error_symbol, data);
1503 conditions = Fget (real_error_symbol, Qerror_conditions);
1505 /* Remember from where signal was called. Skip over the frame for
1506 `signal' itself. If a frame for `error' follows, skip that,
1507 too. Don't do this when ERROR_SYMBOL is nil, because that
1508 is a memory-full error. */
1509 Vsignaling_function = Qnil;
1510 if (!NILP (error_symbol))
1512 union specbinding *pdl = backtrace_next (backtrace_top ());
1513 if (backtrace_p (pdl) && EQ (backtrace_function (pdl), Qerror))
1514 pdl = backtrace_next (pdl);
1515 if (backtrace_p (pdl))
1516 Vsignaling_function = backtrace_function (pdl);
1519 for (h = handlerlist; h; h = h->next)
1521 if (h->type != CONDITION_CASE)
1522 continue;
1523 clause = find_handler_clause (h->tag_or_ch, conditions);
1524 if (!NILP (clause))
1525 break;
1528 if (/* Don't run the debugger for a memory-full error.
1529 (There is no room in memory to do that!) */
1530 !NILP (error_symbol)
1531 && (!NILP (Vdebug_on_signal)
1532 /* If no handler is present now, try to run the debugger. */
1533 || NILP (clause)
1534 /* A `debug' symbol in the handler list disables the normal
1535 suppression of the debugger. */
1536 || (CONSP (clause) && !NILP (Fmemq (Qdebug, clause)))
1537 /* Special handler that means "print a message and run debugger
1538 if requested". */
1539 || EQ (h->tag_or_ch, Qerror)))
1541 bool debugger_called
1542 = maybe_call_debugger (conditions, error_symbol, data);
1543 /* We can't return values to code which signaled an error, but we
1544 can continue code which has signaled a quit. */
1545 if (debugger_called && EQ (real_error_symbol, Qquit))
1546 return Qnil;
1549 if (!NILP (clause))
1551 Lisp_Object unwind_data
1552 = (NILP (error_symbol) ? data : Fcons (error_symbol, data));
1554 unwind_to_catch (h, unwind_data);
1556 else
1558 if (handlerlist != &handlerlist_sentinel)
1559 /* FIXME: This will come right back here if there's no `top-level'
1560 catcher. A better solution would be to abort here, and instead
1561 add a catch-all condition handler so we never come here. */
1562 Fthrow (Qtop_level, Qt);
1565 if (! NILP (error_symbol))
1566 data = Fcons (error_symbol, data);
1568 string = Ferror_message_string (data);
1569 fatal ("%s", SDATA (string));
1572 /* Internal version of Fsignal that never returns.
1573 Used for anything but Qquit (which can return from Fsignal). */
1575 void
1576 xsignal (Lisp_Object error_symbol, Lisp_Object data)
1578 Fsignal (error_symbol, data);
1579 emacs_abort ();
1582 /* Like xsignal, but takes 0, 1, 2, or 3 args instead of a list. */
1584 void
1585 xsignal0 (Lisp_Object error_symbol)
1587 xsignal (error_symbol, Qnil);
1590 void
1591 xsignal1 (Lisp_Object error_symbol, Lisp_Object arg)
1593 xsignal (error_symbol, list1 (arg));
1596 void
1597 xsignal2 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2)
1599 xsignal (error_symbol, list2 (arg1, arg2));
1602 void
1603 xsignal3 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
1605 xsignal (error_symbol, list3 (arg1, arg2, arg3));
1608 /* Signal `error' with message S, and additional arg ARG.
1609 If ARG is not a genuine list, make it a one-element list. */
1611 void
1612 signal_error (const char *s, Lisp_Object arg)
1614 Lisp_Object tortoise, hare;
1616 hare = tortoise = arg;
1617 while (CONSP (hare))
1619 hare = XCDR (hare);
1620 if (!CONSP (hare))
1621 break;
1623 hare = XCDR (hare);
1624 tortoise = XCDR (tortoise);
1626 if (EQ (hare, tortoise))
1627 break;
1630 if (!NILP (hare))
1631 arg = list1 (arg);
1633 xsignal (Qerror, Fcons (build_string (s), arg));
1637 /* Return true if LIST is a non-nil atom or
1638 a list containing one of CONDITIONS. */
1640 static bool
1641 wants_debugger (Lisp_Object list, Lisp_Object conditions)
1643 if (NILP (list))
1644 return 0;
1645 if (! CONSP (list))
1646 return 1;
1648 while (CONSP (conditions))
1650 Lisp_Object this, tail;
1651 this = XCAR (conditions);
1652 for (tail = list; CONSP (tail); tail = XCDR (tail))
1653 if (EQ (XCAR (tail), this))
1654 return 1;
1655 conditions = XCDR (conditions);
1657 return 0;
1660 /* Return true if an error with condition-symbols CONDITIONS,
1661 and described by SIGNAL-DATA, should skip the debugger
1662 according to debugger-ignored-errors. */
1664 static bool
1665 skip_debugger (Lisp_Object conditions, Lisp_Object data)
1667 Lisp_Object tail;
1668 bool first_string = 1;
1669 Lisp_Object error_message;
1671 error_message = Qnil;
1672 for (tail = Vdebug_ignored_errors; CONSP (tail); tail = XCDR (tail))
1674 if (STRINGP (XCAR (tail)))
1676 if (first_string)
1678 error_message = Ferror_message_string (data);
1679 first_string = 0;
1682 if (fast_string_match (XCAR (tail), error_message) >= 0)
1683 return 1;
1685 else
1687 Lisp_Object contail;
1689 for (contail = conditions; CONSP (contail); contail = XCDR (contail))
1690 if (EQ (XCAR (tail), XCAR (contail)))
1691 return 1;
1695 return 0;
1698 /* Call the debugger if calling it is currently enabled for CONDITIONS.
1699 SIG and DATA describe the signal. There are two ways to pass them:
1700 = SIG is the error symbol, and DATA is the rest of the data.
1701 = SIG is nil, and DATA is (SYMBOL . REST-OF-DATA).
1702 This is for memory-full errors only. */
1703 static bool
1704 maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig, Lisp_Object data)
1706 Lisp_Object combined_data;
1708 combined_data = Fcons (sig, data);
1710 if (
1711 /* Don't try to run the debugger with interrupts blocked.
1712 The editing loop would return anyway. */
1713 ! input_blocked_p ()
1714 && NILP (Vinhibit_debugger)
1715 /* Does user want to enter debugger for this kind of error? */
1716 && (EQ (sig, Qquit)
1717 ? debug_on_quit
1718 : wants_debugger (Vdebug_on_error, conditions))
1719 && ! skip_debugger (conditions, combined_data)
1720 /* RMS: What's this for? */
1721 && when_entered_debugger < num_nonmacro_input_events)
1723 call_debugger (list2 (Qerror, combined_data));
1724 return 1;
1727 return 0;
1730 static Lisp_Object
1731 find_handler_clause (Lisp_Object handlers, Lisp_Object conditions)
1733 register Lisp_Object h;
1735 /* t is used by handlers for all conditions, set up by C code. */
1736 if (EQ (handlers, Qt))
1737 return Qt;
1739 /* error is used similarly, but means print an error message
1740 and run the debugger if that is enabled. */
1741 if (EQ (handlers, Qerror))
1742 return Qt;
1744 for (h = handlers; CONSP (h); h = XCDR (h))
1746 Lisp_Object handler = XCAR (h);
1747 if (!NILP (Fmemq (handler, conditions)))
1748 return handlers;
1751 return Qnil;
1755 /* Dump an error message; called like vprintf. */
1756 void
1757 verror (const char *m, va_list ap)
1759 char buf[4000];
1760 ptrdiff_t size = sizeof buf;
1761 ptrdiff_t size_max = STRING_BYTES_BOUND + 1;
1762 char *buffer = buf;
1763 ptrdiff_t used;
1764 Lisp_Object string;
1766 used = evxprintf (&buffer, &size, buf, size_max, m, ap);
1767 string = make_string (buffer, used);
1768 if (buffer != buf)
1769 xfree (buffer);
1771 xsignal1 (Qerror, string);
1775 /* Dump an error message; called like printf. */
1777 /* VARARGS 1 */
1778 void
1779 error (const char *m, ...)
1781 va_list ap;
1782 va_start (ap, m);
1783 verror (m, ap);
1786 DEFUN ("commandp", Fcommandp, Scommandp, 1, 2, 0,
1787 doc: /* Non-nil if FUNCTION makes provisions for interactive calling.
1788 This means it contains a description for how to read arguments to give it.
1789 The value is nil for an invalid function or a symbol with no function
1790 definition.
1792 Interactively callable functions include strings and vectors (treated
1793 as keyboard macros), lambda-expressions that contain a top-level call
1794 to `interactive', autoload definitions made by `autoload' with non-nil
1795 fourth argument, and some of the built-in functions of Lisp.
1797 Also, a symbol satisfies `commandp' if its function definition does so.
1799 If the optional argument FOR-CALL-INTERACTIVELY is non-nil,
1800 then strings and vectors are not accepted. */)
1801 (Lisp_Object function, Lisp_Object for_call_interactively)
1803 register Lisp_Object fun;
1804 register Lisp_Object funcar;
1805 Lisp_Object if_prop = Qnil;
1807 fun = function;
1809 fun = indirect_function (fun); /* Check cycles. */
1810 if (NILP (fun))
1811 return Qnil;
1813 /* Check an `interactive-form' property if present, analogous to the
1814 function-documentation property. */
1815 fun = function;
1816 while (SYMBOLP (fun))
1818 Lisp_Object tmp = Fget (fun, Qinteractive_form);
1819 if (!NILP (tmp))
1820 if_prop = Qt;
1821 fun = Fsymbol_function (fun);
1824 /* Emacs primitives are interactive if their DEFUN specifies an
1825 interactive spec. */
1826 if (SUBRP (fun))
1827 return XSUBR (fun)->intspec ? Qt : if_prop;
1829 /* Bytecode objects are interactive if they are long enough to
1830 have an element whose index is COMPILED_INTERACTIVE, which is
1831 where the interactive spec is stored. */
1832 else if (COMPILEDP (fun))
1833 return ((ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK) > COMPILED_INTERACTIVE
1834 ? Qt : if_prop);
1836 /* Strings and vectors are keyboard macros. */
1837 if (STRINGP (fun) || VECTORP (fun))
1838 return (NILP (for_call_interactively) ? Qt : Qnil);
1840 /* Lists may represent commands. */
1841 if (!CONSP (fun))
1842 return Qnil;
1843 funcar = XCAR (fun);
1844 if (EQ (funcar, Qclosure))
1845 return (!NILP (Fassq (Qinteractive, Fcdr (Fcdr (XCDR (fun)))))
1846 ? Qt : if_prop);
1847 else if (EQ (funcar, Qlambda))
1848 return !NILP (Fassq (Qinteractive, Fcdr (XCDR (fun)))) ? Qt : if_prop;
1849 else if (EQ (funcar, Qautoload))
1850 return !NILP (Fcar (Fcdr (Fcdr (XCDR (fun))))) ? Qt : if_prop;
1851 else
1852 return Qnil;
1855 DEFUN ("autoload", Fautoload, Sautoload, 2, 5, 0,
1856 doc: /* Define FUNCTION to autoload from FILE.
1857 FUNCTION is a symbol; FILE is a file name string to pass to `load'.
1858 Third arg DOCSTRING is documentation for the function.
1859 Fourth arg INTERACTIVE if non-nil says function can be called interactively.
1860 Fifth arg TYPE indicates the type of the object:
1861 nil or omitted says FUNCTION is a function,
1862 `keymap' says FUNCTION is really a keymap, and
1863 `macro' or t says FUNCTION is really a macro.
1864 Third through fifth args give info about the real definition.
1865 They default to nil.
1866 If FUNCTION is already defined other than as an autoload,
1867 this does nothing and returns nil. */)
1868 (Lisp_Object function, Lisp_Object file, Lisp_Object docstring, Lisp_Object interactive, Lisp_Object type)
1870 CHECK_SYMBOL (function);
1871 CHECK_STRING (file);
1873 /* If function is defined and not as an autoload, don't override. */
1874 if (!NILP (XSYMBOL (function)->function)
1875 && !AUTOLOADP (XSYMBOL (function)->function))
1876 return Qnil;
1878 if (!NILP (Vpurify_flag) && EQ (docstring, make_number (0)))
1879 /* `read1' in lread.c has found the docstring starting with "\
1880 and assumed the docstring will be provided by Snarf-documentation, so it
1881 passed us 0 instead. But that leads to accidental sharing in purecopy's
1882 hash-consing, so we use a (hopefully) unique integer instead. */
1883 docstring = make_number (XHASH (function));
1884 return Fdefalias (function,
1885 list5 (Qautoload, file, docstring, interactive, type),
1886 Qnil);
1889 void
1890 un_autoload (Lisp_Object oldqueue)
1892 Lisp_Object queue, first, second;
1894 /* Queue to unwind is current value of Vautoload_queue.
1895 oldqueue is the shadowed value to leave in Vautoload_queue. */
1896 queue = Vautoload_queue;
1897 Vautoload_queue = oldqueue;
1898 while (CONSP (queue))
1900 first = XCAR (queue);
1901 second = Fcdr (first);
1902 first = Fcar (first);
1903 if (EQ (first, make_number (0)))
1904 Vfeatures = second;
1905 else
1906 Ffset (first, second);
1907 queue = XCDR (queue);
1911 /* Load an autoloaded function.
1912 FUNNAME is the symbol which is the function's name.
1913 FUNDEF is the autoload definition (a list). */
1915 DEFUN ("autoload-do-load", Fautoload_do_load, Sautoload_do_load, 1, 3, 0,
1916 doc: /* Load FUNDEF which should be an autoload.
1917 If non-nil, FUNNAME should be the symbol whose function value is FUNDEF,
1918 in which case the function returns the new autoloaded function value.
1919 If equal to `macro', MACRO-ONLY specifies that FUNDEF should only be loaded if
1920 it defines a macro. */)
1921 (Lisp_Object fundef, Lisp_Object funname, Lisp_Object macro_only)
1923 ptrdiff_t count = SPECPDL_INDEX ();
1924 struct gcpro gcpro1, gcpro2, gcpro3;
1926 if (!CONSP (fundef) || !EQ (Qautoload, XCAR (fundef)))
1927 return fundef;
1929 if (EQ (macro_only, Qmacro))
1931 Lisp_Object kind = Fnth (make_number (4), fundef);
1932 if (! (EQ (kind, Qt) || EQ (kind, Qmacro)))
1933 return fundef;
1936 /* This is to make sure that loadup.el gives a clear picture
1937 of what files are preloaded and when. */
1938 if (! NILP (Vpurify_flag))
1939 error ("Attempt to autoload %s while preparing to dump",
1940 SDATA (SYMBOL_NAME (funname)));
1942 CHECK_SYMBOL (funname);
1943 GCPRO3 (funname, fundef, macro_only);
1945 /* Preserve the match data. */
1946 record_unwind_save_match_data ();
1948 /* If autoloading gets an error (which includes the error of failing
1949 to define the function being called), we use Vautoload_queue
1950 to undo function definitions and `provide' calls made by
1951 the function. We do this in the specific case of autoloading
1952 because autoloading is not an explicit request "load this file",
1953 but rather a request to "call this function".
1955 The value saved here is to be restored into Vautoload_queue. */
1956 record_unwind_protect (un_autoload, Vautoload_queue);
1957 Vautoload_queue = Qt;
1958 /* If `macro_only', assume this autoload to be a "best-effort",
1959 so don't signal an error if autoloading fails. */
1960 Fload (Fcar (Fcdr (fundef)), macro_only, Qt, Qnil, Qt);
1962 /* Once loading finishes, don't undo it. */
1963 Vautoload_queue = Qt;
1964 unbind_to (count, Qnil);
1966 UNGCPRO;
1968 if (NILP (funname))
1969 return Qnil;
1970 else
1972 Lisp_Object fun = Findirect_function (funname, Qnil);
1974 if (!NILP (Fequal (fun, fundef)))
1975 error ("Autoloading failed to define function %s",
1976 SDATA (SYMBOL_NAME (funname)));
1977 else
1978 return fun;
1983 DEFUN ("eval", Feval, Seval, 1, 2, 0,
1984 doc: /* Evaluate FORM and return its value.
1985 If LEXICAL is t, evaluate using lexical scoping.
1986 LEXICAL can also be an actual lexical environment, in the form of an
1987 alist mapping symbols to their value. */)
1988 (Lisp_Object form, Lisp_Object lexical)
1990 ptrdiff_t count = SPECPDL_INDEX ();
1991 specbind (Qinternal_interpreter_environment,
1992 CONSP (lexical) || NILP (lexical) ? lexical : list1 (Qt));
1993 return unbind_to (count, eval_sub (form));
1996 /* Grow the specpdl stack by one entry.
1997 The caller should have already initialized the entry.
1998 Signal an error on stack overflow.
2000 Make sure that there is always one unused entry past the top of the
2001 stack, so that the just-initialized entry is safely unwound if
2002 memory exhausted and an error is signaled here. Also, allocate a
2003 never-used entry just before the bottom of the stack; sometimes its
2004 address is taken. */
2006 static void
2007 grow_specpdl (void)
2009 specpdl_ptr++;
2011 if (specpdl_ptr == specpdl + specpdl_size)
2013 ptrdiff_t count = SPECPDL_INDEX ();
2014 ptrdiff_t max_size = min (max_specpdl_size, PTRDIFF_MAX - 1000);
2015 union specbinding *pdlvec = specpdl - 1;
2016 ptrdiff_t pdlvecsize = specpdl_size + 1;
2017 if (max_size <= specpdl_size)
2019 if (max_specpdl_size < 400)
2020 max_size = max_specpdl_size = 400;
2021 if (max_size <= specpdl_size)
2022 signal_error ("Variable binding depth exceeds max-specpdl-size",
2023 Qnil);
2025 pdlvec = xpalloc (pdlvec, &pdlvecsize, 1, max_size + 1, sizeof *specpdl);
2026 specpdl = pdlvec + 1;
2027 specpdl_size = pdlvecsize - 1;
2028 specpdl_ptr = specpdl + count;
2032 ptrdiff_t
2033 record_in_backtrace (Lisp_Object function, Lisp_Object *args, ptrdiff_t nargs)
2035 ptrdiff_t count = SPECPDL_INDEX ();
2037 eassert (nargs >= UNEVALLED);
2038 specpdl_ptr->bt.kind = SPECPDL_BACKTRACE;
2039 specpdl_ptr->bt.debug_on_exit = false;
2040 specpdl_ptr->bt.function = function;
2041 specpdl_ptr->bt.args = args;
2042 specpdl_ptr->bt.nargs = nargs;
2043 grow_specpdl ();
2045 return count;
2048 /* Eval a sub-expression of the current expression (i.e. in the same
2049 lexical scope). */
2050 Lisp_Object
2051 eval_sub (Lisp_Object form)
2053 Lisp_Object fun, val, original_fun, original_args;
2054 Lisp_Object funcar;
2055 struct gcpro gcpro1, gcpro2, gcpro3;
2056 ptrdiff_t count;
2058 if (SYMBOLP (form))
2060 /* Look up its binding in the lexical environment.
2061 We do not pay attention to the declared_special flag here, since we
2062 already did that when let-binding the variable. */
2063 Lisp_Object lex_binding
2064 = !NILP (Vinternal_interpreter_environment) /* Mere optimization! */
2065 ? Fassq (form, Vinternal_interpreter_environment)
2066 : Qnil;
2067 if (CONSP (lex_binding))
2068 return XCDR (lex_binding);
2069 else
2070 return Fsymbol_value (form);
2073 if (!CONSP (form))
2074 return form;
2076 QUIT;
2078 GCPRO1 (form);
2079 maybe_gc ();
2080 UNGCPRO;
2082 if (++lisp_eval_depth > max_lisp_eval_depth)
2084 if (max_lisp_eval_depth < 100)
2085 max_lisp_eval_depth = 100;
2086 if (lisp_eval_depth > max_lisp_eval_depth)
2087 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2090 original_fun = XCAR (form);
2091 original_args = XCDR (form);
2093 /* This also protects them from gc. */
2094 count = record_in_backtrace (original_fun, &original_args, UNEVALLED);
2096 if (debug_on_next_call)
2097 do_debug_on_call (Qt, count);
2099 /* At this point, only original_fun and original_args
2100 have values that will be used below. */
2101 retry:
2103 /* Optimize for no indirection. */
2104 fun = original_fun;
2105 if (!SYMBOLP (fun))
2106 fun = Ffunction (Fcons (fun, Qnil));
2107 else if (!NILP (fun) && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2108 fun = indirect_function (fun);
2110 if (SUBRP (fun))
2112 Lisp_Object numargs;
2113 Lisp_Object argvals[8];
2114 Lisp_Object args_left;
2115 register int i, maxargs;
2117 args_left = original_args;
2118 numargs = Flength (args_left);
2120 check_cons_list ();
2122 if (XINT (numargs) < XSUBR (fun)->min_args
2123 || (XSUBR (fun)->max_args >= 0
2124 && XSUBR (fun)->max_args < XINT (numargs)))
2125 xsignal2 (Qwrong_number_of_arguments, original_fun, numargs);
2127 else if (XSUBR (fun)->max_args == UNEVALLED)
2128 val = (XSUBR (fun)->function.aUNEVALLED) (args_left);
2129 else if (XSUBR (fun)->max_args == MANY)
2131 /* Pass a vector of evaluated arguments. */
2132 Lisp_Object *vals;
2133 ptrdiff_t argnum = 0;
2134 USE_SAFE_ALLOCA;
2136 SAFE_ALLOCA_LISP (vals, XINT (numargs));
2138 GCPRO3 (args_left, fun, fun);
2139 gcpro3.var = vals;
2140 gcpro3.nvars = 0;
2142 while (!NILP (args_left))
2144 vals[argnum++] = eval_sub (Fcar (args_left));
2145 args_left = Fcdr (args_left);
2146 gcpro3.nvars = argnum;
2149 set_backtrace_args (specpdl + count, vals, XINT (numargs));
2151 val = (XSUBR (fun)->function.aMANY) (XINT (numargs), vals);
2152 UNGCPRO;
2153 SAFE_FREE ();
2155 else
2157 GCPRO3 (args_left, fun, fun);
2158 gcpro3.var = argvals;
2159 gcpro3.nvars = 0;
2161 maxargs = XSUBR (fun)->max_args;
2162 for (i = 0; i < maxargs; args_left = Fcdr (args_left))
2164 argvals[i] = eval_sub (Fcar (args_left));
2165 gcpro3.nvars = ++i;
2168 UNGCPRO;
2170 set_backtrace_args (specpdl + count, argvals, XINT (numargs));
2172 switch (i)
2174 case 0:
2175 val = (XSUBR (fun)->function.a0 ());
2176 break;
2177 case 1:
2178 val = (XSUBR (fun)->function.a1 (argvals[0]));
2179 break;
2180 case 2:
2181 val = (XSUBR (fun)->function.a2 (argvals[0], argvals[1]));
2182 break;
2183 case 3:
2184 val = (XSUBR (fun)->function.a3
2185 (argvals[0], argvals[1], argvals[2]));
2186 break;
2187 case 4:
2188 val = (XSUBR (fun)->function.a4
2189 (argvals[0], argvals[1], argvals[2], argvals[3]));
2190 break;
2191 case 5:
2192 val = (XSUBR (fun)->function.a5
2193 (argvals[0], argvals[1], argvals[2], argvals[3],
2194 argvals[4]));
2195 break;
2196 case 6:
2197 val = (XSUBR (fun)->function.a6
2198 (argvals[0], argvals[1], argvals[2], argvals[3],
2199 argvals[4], argvals[5]));
2200 break;
2201 case 7:
2202 val = (XSUBR (fun)->function.a7
2203 (argvals[0], argvals[1], argvals[2], argvals[3],
2204 argvals[4], argvals[5], argvals[6]));
2205 break;
2207 case 8:
2208 val = (XSUBR (fun)->function.a8
2209 (argvals[0], argvals[1], argvals[2], argvals[3],
2210 argvals[4], argvals[5], argvals[6], argvals[7]));
2211 break;
2213 default:
2214 /* Someone has created a subr that takes more arguments than
2215 is supported by this code. We need to either rewrite the
2216 subr to use a different argument protocol, or add more
2217 cases to this switch. */
2218 emacs_abort ();
2222 else if (COMPILEDP (fun))
2223 val = apply_lambda (fun, original_args, count);
2224 else
2226 if (NILP (fun))
2227 xsignal1 (Qvoid_function, original_fun);
2228 if (!CONSP (fun))
2229 xsignal1 (Qinvalid_function, original_fun);
2230 funcar = XCAR (fun);
2231 if (!SYMBOLP (funcar))
2232 xsignal1 (Qinvalid_function, original_fun);
2233 if (EQ (funcar, Qautoload))
2235 Fautoload_do_load (fun, original_fun, Qnil);
2236 goto retry;
2238 if (EQ (funcar, Qmacro))
2240 ptrdiff_t count1 = SPECPDL_INDEX ();
2241 Lisp_Object exp;
2242 /* Bind lexical-binding during expansion of the macro, so the
2243 macro can know reliably if the code it outputs will be
2244 interpreted using lexical-binding or not. */
2245 specbind (Qlexical_binding,
2246 NILP (Vinternal_interpreter_environment) ? Qnil : Qt);
2247 exp = apply1 (Fcdr (fun), original_args);
2248 unbind_to (count1, Qnil);
2249 val = eval_sub (exp);
2251 else if (EQ (funcar, Qlambda)
2252 || EQ (funcar, Qclosure))
2253 val = apply_lambda (fun, original_args, count);
2254 else
2255 xsignal1 (Qinvalid_function, original_fun);
2257 check_cons_list ();
2259 lisp_eval_depth--;
2260 if (backtrace_debug_on_exit (specpdl + count))
2261 val = call_debugger (list2 (Qexit, val));
2262 specpdl_ptr--;
2264 return val;
2267 DEFUN ("apply", Fapply, Sapply, 1, MANY, 0,
2268 doc: /* Call FUNCTION with our remaining args, using our last arg as list of args.
2269 Then return the value FUNCTION returns.
2270 Thus, (apply '+ 1 2 '(3 4)) returns 10.
2271 usage: (apply FUNCTION &rest ARGUMENTS) */)
2272 (ptrdiff_t nargs, Lisp_Object *args)
2274 ptrdiff_t i, numargs, funcall_nargs;
2275 register Lisp_Object *funcall_args = NULL;
2276 register Lisp_Object spread_arg = args[nargs - 1];
2277 Lisp_Object fun = args[0];
2278 Lisp_Object retval;
2279 USE_SAFE_ALLOCA;
2281 CHECK_LIST (spread_arg);
2283 numargs = XINT (Flength (spread_arg));
2285 if (numargs == 0)
2286 return Ffuncall (nargs - 1, args);
2287 else if (numargs == 1)
2289 args [nargs - 1] = XCAR (spread_arg);
2290 return Ffuncall (nargs, args);
2293 numargs += nargs - 2;
2295 /* Optimize for no indirection. */
2296 if (SYMBOLP (fun) && !NILP (fun)
2297 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2299 fun = indirect_function (fun);
2300 if (NILP (fun))
2301 /* Let funcall get the error. */
2302 fun = args[0];
2305 if (SUBRP (fun) && XSUBR (fun)->max_args > numargs
2306 /* Don't hide an error by adding missing arguments. */
2307 && numargs >= XSUBR (fun)->min_args)
2309 /* Avoid making funcall cons up a yet another new vector of arguments
2310 by explicitly supplying nil's for optional values. */
2311 SAFE_ALLOCA_LISP (funcall_args, 1 + XSUBR (fun)->max_args);
2312 for (i = numargs; i < XSUBR (fun)->max_args; /* nothing */)
2313 funcall_args[++i] = Qnil;
2314 funcall_nargs = 1 + XSUBR (fun)->max_args;
2316 else
2317 { /* We add 1 to numargs because funcall_args includes the
2318 function itself as well as its arguments. */
2319 SAFE_ALLOCA_LISP (funcall_args, 1 + numargs);
2320 funcall_nargs = 1 + numargs;
2323 memcpy (funcall_args, args, nargs * word_size);
2324 /* Spread the last arg we got. Its first element goes in
2325 the slot that it used to occupy, hence this value of I. */
2326 i = nargs - 1;
2327 while (!NILP (spread_arg))
2329 funcall_args [i++] = XCAR (spread_arg);
2330 spread_arg = XCDR (spread_arg);
2333 /* Ffuncall gcpro's all of its args. */
2334 retval = Ffuncall (funcall_nargs, funcall_args);
2336 SAFE_FREE ();
2337 return retval;
2340 /* Run hook variables in various ways. */
2342 static Lisp_Object
2343 funcall_nil (ptrdiff_t nargs, Lisp_Object *args)
2345 Ffuncall (nargs, args);
2346 return Qnil;
2349 DEFUN ("run-hooks", Frun_hooks, Srun_hooks, 0, MANY, 0,
2350 doc: /* Run each hook in HOOKS.
2351 Each argument should be a symbol, a hook variable.
2352 These symbols are processed in the order specified.
2353 If a hook symbol has a non-nil value, that value may be a function
2354 or a list of functions to be called to run the hook.
2355 If the value is a function, it is called with no arguments.
2356 If it is a list, the elements are called, in order, with no arguments.
2358 Major modes should not use this function directly to run their mode
2359 hook; they should use `run-mode-hooks' instead.
2361 Do not use `make-local-variable' to make a hook variable buffer-local.
2362 Instead, use `add-hook' and specify t for the LOCAL argument.
2363 usage: (run-hooks &rest HOOKS) */)
2364 (ptrdiff_t nargs, Lisp_Object *args)
2366 Lisp_Object hook[1];
2367 ptrdiff_t i;
2369 for (i = 0; i < nargs; i++)
2371 hook[0] = args[i];
2372 run_hook_with_args (1, hook, funcall_nil);
2375 return Qnil;
2378 DEFUN ("run-hook-with-args", Frun_hook_with_args,
2379 Srun_hook_with_args, 1, MANY, 0,
2380 doc: /* Run HOOK with the specified arguments ARGS.
2381 HOOK should be a symbol, a hook variable. The value of HOOK
2382 may be nil, a function, or a list of functions. Call each
2383 function in order with arguments ARGS. The final return value
2384 is unspecified.
2386 Do not use `make-local-variable' to make a hook variable buffer-local.
2387 Instead, use `add-hook' and specify t for the LOCAL argument.
2388 usage: (run-hook-with-args HOOK &rest ARGS) */)
2389 (ptrdiff_t nargs, Lisp_Object *args)
2391 return run_hook_with_args (nargs, args, funcall_nil);
2394 /* NB this one still documents a specific non-nil return value.
2395 (As did run-hook-with-args and run-hook-with-args-until-failure
2396 until they were changed in 24.1.) */
2397 DEFUN ("run-hook-with-args-until-success", Frun_hook_with_args_until_success,
2398 Srun_hook_with_args_until_success, 1, MANY, 0,
2399 doc: /* Run HOOK with the specified arguments ARGS.
2400 HOOK should be a symbol, a hook variable. The value of HOOK
2401 may be nil, a function, or a list of functions. Call each
2402 function in order with arguments ARGS, stopping at the first
2403 one that returns non-nil, and return that value. Otherwise (if
2404 all functions return nil, or if there are no functions to call),
2405 return nil.
2407 Do not use `make-local-variable' to make a hook variable buffer-local.
2408 Instead, use `add-hook' and specify t for the LOCAL argument.
2409 usage: (run-hook-with-args-until-success HOOK &rest ARGS) */)
2410 (ptrdiff_t nargs, Lisp_Object *args)
2412 return run_hook_with_args (nargs, args, Ffuncall);
2415 static Lisp_Object
2416 funcall_not (ptrdiff_t nargs, Lisp_Object *args)
2418 return NILP (Ffuncall (nargs, args)) ? Qt : Qnil;
2421 DEFUN ("run-hook-with-args-until-failure", Frun_hook_with_args_until_failure,
2422 Srun_hook_with_args_until_failure, 1, MANY, 0,
2423 doc: /* Run HOOK with the specified arguments ARGS.
2424 HOOK should be a symbol, a hook variable. The value of HOOK
2425 may be nil, a function, or a list of functions. Call each
2426 function in order with arguments ARGS, stopping at the first
2427 one that returns nil, and return nil. Otherwise (if all functions
2428 return non-nil, or if there are no functions to call), return non-nil
2429 \(do not rely on the precise return value in this case).
2431 Do not use `make-local-variable' to make a hook variable buffer-local.
2432 Instead, use `add-hook' and specify t for the LOCAL argument.
2433 usage: (run-hook-with-args-until-failure HOOK &rest ARGS) */)
2434 (ptrdiff_t nargs, Lisp_Object *args)
2436 return NILP (run_hook_with_args (nargs, args, funcall_not)) ? Qt : Qnil;
2439 static Lisp_Object
2440 run_hook_wrapped_funcall (ptrdiff_t nargs, Lisp_Object *args)
2442 Lisp_Object tmp = args[0], ret;
2443 args[0] = args[1];
2444 args[1] = tmp;
2445 ret = Ffuncall (nargs, args);
2446 args[1] = args[0];
2447 args[0] = tmp;
2448 return ret;
2451 DEFUN ("run-hook-wrapped", Frun_hook_wrapped, Srun_hook_wrapped, 2, MANY, 0,
2452 doc: /* Run HOOK, passing each function through WRAP-FUNCTION.
2453 I.e. instead of calling each function FUN directly with arguments ARGS,
2454 it calls WRAP-FUNCTION with arguments FUN and ARGS.
2455 As soon as a call to WRAP-FUNCTION returns non-nil, `run-hook-wrapped'
2456 aborts and returns that value.
2457 usage: (run-hook-wrapped HOOK WRAP-FUNCTION &rest ARGS) */)
2458 (ptrdiff_t nargs, Lisp_Object *args)
2460 return run_hook_with_args (nargs, args, run_hook_wrapped_funcall);
2463 /* ARGS[0] should be a hook symbol.
2464 Call each of the functions in the hook value, passing each of them
2465 as arguments all the rest of ARGS (all NARGS - 1 elements).
2466 FUNCALL specifies how to call each function on the hook.
2467 The caller (or its caller, etc) must gcpro all of ARGS,
2468 except that it isn't necessary to gcpro ARGS[0]. */
2470 Lisp_Object
2471 run_hook_with_args (ptrdiff_t nargs, Lisp_Object *args,
2472 Lisp_Object (*funcall) (ptrdiff_t nargs, Lisp_Object *args))
2474 Lisp_Object sym, val, ret = Qnil;
2475 struct gcpro gcpro1, gcpro2, gcpro3;
2477 /* If we are dying or still initializing,
2478 don't do anything--it would probably crash if we tried. */
2479 if (NILP (Vrun_hooks))
2480 return Qnil;
2482 sym = args[0];
2483 val = find_symbol_value (sym);
2485 if (EQ (val, Qunbound) || NILP (val))
2486 return ret;
2487 else if (!CONSP (val) || FUNCTIONP (val))
2489 args[0] = val;
2490 return funcall (nargs, args);
2492 else
2494 Lisp_Object global_vals = Qnil;
2495 GCPRO3 (sym, val, global_vals);
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 UNGCPRO;
2535 return ret;
2539 /* Run the hook HOOK, giving each function the two args ARG1 and ARG2. */
2541 void
2542 run_hook_with_args_2 (Lisp_Object hook, Lisp_Object arg1, Lisp_Object arg2)
2544 Frun_hook_with_args (3, ((Lisp_Object []) { hook, arg1, arg2 }));
2547 /* Apply fn to arg. */
2548 Lisp_Object
2549 apply1 (Lisp_Object fn, Lisp_Object arg)
2551 return (NILP (arg) ? Ffuncall (1, &fn)
2552 : Fapply (2, ((Lisp_Object []) { fn, arg })));
2555 /* Call function fn on no arguments. */
2556 Lisp_Object
2557 call0 (Lisp_Object fn)
2559 return Ffuncall (1, &fn);
2562 /* Call function fn with 1 argument arg1. */
2563 /* ARGSUSED */
2564 Lisp_Object
2565 call1 (Lisp_Object fn, Lisp_Object arg1)
2567 return Ffuncall (2, ((Lisp_Object []) { fn, arg1 }));
2570 /* Call function fn with 2 arguments arg1, arg2. */
2571 /* ARGSUSED */
2572 Lisp_Object
2573 call2 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2)
2575 return Ffuncall (3, ((Lisp_Object []) { fn, arg1, arg2 }));
2578 /* Call function fn with 3 arguments arg1, arg2, arg3. */
2579 /* ARGSUSED */
2580 Lisp_Object
2581 call3 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2583 return Ffuncall (4, ((Lisp_Object []) { fn, arg1, arg2, arg3 }));
2586 /* Call function fn with 4 arguments arg1, arg2, arg3, arg4. */
2587 /* ARGSUSED */
2588 Lisp_Object
2589 call4 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2590 Lisp_Object arg4)
2592 return Ffuncall (5, ((Lisp_Object []) { fn, arg1, arg2, arg3, arg4 }));
2595 /* Call function fn with 5 arguments arg1, arg2, arg3, arg4, arg5. */
2596 /* ARGSUSED */
2597 Lisp_Object
2598 call5 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2599 Lisp_Object arg4, Lisp_Object arg5)
2601 return Ffuncall (6, ((Lisp_Object []) { fn, arg1, arg2, arg3, arg4, arg5 }));
2604 /* Call function fn with 6 arguments arg1, arg2, arg3, arg4, arg5, arg6. */
2605 /* ARGSUSED */
2606 Lisp_Object
2607 call6 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2608 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6)
2610 return Ffuncall (7, ((Lisp_Object [])
2611 { fn, arg1, arg2, arg3, arg4, arg5, arg6 }));
2614 /* Call function fn with 7 arguments arg1, arg2, arg3, arg4, arg5, arg6, arg7. */
2615 /* ARGSUSED */
2616 Lisp_Object
2617 call7 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2618 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6, Lisp_Object arg7)
2620 return Ffuncall (8, ((Lisp_Object [])
2621 { fn, arg1, arg2, arg3, arg4, arg5, arg6, arg7 }));
2624 /* The caller should GCPRO all the elements of ARGS. */
2626 DEFUN ("functionp", Ffunctionp, Sfunctionp, 1, 1, 0,
2627 doc: /* Non-nil if OBJECT is a function. */)
2628 (Lisp_Object object)
2630 if (FUNCTIONP (object))
2631 return Qt;
2632 return Qnil;
2635 DEFUN ("funcall", Ffuncall, Sfuncall, 1, MANY, 0,
2636 doc: /* Call first argument as a function, passing remaining arguments to it.
2637 Return the value that function returns.
2638 Thus, (funcall 'cons 'x 'y) returns (x . y).
2639 usage: (funcall FUNCTION &rest ARGUMENTS) */)
2640 (ptrdiff_t nargs, Lisp_Object *args)
2642 Lisp_Object fun, original_fun;
2643 Lisp_Object funcar;
2644 ptrdiff_t numargs = nargs - 1;
2645 Lisp_Object lisp_numargs;
2646 Lisp_Object val;
2647 register Lisp_Object *internal_args;
2648 ptrdiff_t i, count;
2650 QUIT;
2652 if (++lisp_eval_depth > max_lisp_eval_depth)
2654 if (max_lisp_eval_depth < 100)
2655 max_lisp_eval_depth = 100;
2656 if (lisp_eval_depth > max_lisp_eval_depth)
2657 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2660 /* This also GCPROs them. */
2661 count = record_in_backtrace (args[0], &args[1], nargs - 1);
2663 /* Call GC after setting up the backtrace, so the latter GCPROs the args. */
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 for (i = numargs; i < XSUBR (fun)->max_args; i++)
2704 internal_args[i] = Qnil;
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 register Lisp_Object *arg_vector;
2800 struct gcpro gcpro1, gcpro2, gcpro3;
2801 register Lisp_Object tem;
2802 USE_SAFE_ALLOCA;
2804 numargs = XFASTINT (Flength (args));
2805 SAFE_ALLOCA_LISP (arg_vector, numargs);
2806 args_left = args;
2808 GCPRO3 (*arg_vector, args_left, fun);
2809 gcpro1.nvars = 0;
2811 for (i = 0; i < numargs; )
2813 tem = Fcar (args_left), args_left = Fcdr (args_left);
2814 tem = eval_sub (tem);
2815 arg_vector[i++] = tem;
2816 gcpro1.nvars = i;
2819 UNGCPRO;
2821 set_backtrace_args (specpdl + count, arg_vector, i);
2822 tem = funcall_lambda (fun, numargs, arg_vector);
2824 /* Do the debug-on-exit now, while arg_vector still exists. */
2825 if (backtrace_debug_on_exit (specpdl + count))
2827 /* Don't do it again when we return to eval. */
2828 set_backtrace_debug_on_exit (specpdl + count, false);
2829 tem = call_debugger (list2 (Qexit, tem));
2831 SAFE_FREE ();
2832 return tem;
2835 /* Apply a Lisp function FUN to the NARGS evaluated arguments in ARG_VECTOR
2836 and return the result of evaluation.
2837 FUN must be either a lambda-expression or a compiled-code object. */
2839 static Lisp_Object
2840 funcall_lambda (Lisp_Object fun, ptrdiff_t nargs,
2841 register Lisp_Object *arg_vector)
2843 Lisp_Object val, syms_left, next, lexenv;
2844 ptrdiff_t count = SPECPDL_INDEX ();
2845 ptrdiff_t i;
2846 bool optional, rest;
2848 if (CONSP (fun))
2850 if (EQ (XCAR (fun), Qclosure))
2852 fun = XCDR (fun); /* Drop `closure'. */
2853 lexenv = XCAR (fun);
2854 CHECK_LIST_CONS (fun, fun);
2856 else
2857 lexenv = Qnil;
2858 syms_left = XCDR (fun);
2859 if (CONSP (syms_left))
2860 syms_left = XCAR (syms_left);
2861 else
2862 xsignal1 (Qinvalid_function, fun);
2864 else if (COMPILEDP (fun))
2866 syms_left = AREF (fun, COMPILED_ARGLIST);
2867 if (INTEGERP (syms_left))
2868 /* A byte-code object with a non-nil `push args' slot means we
2869 shouldn't bind any arguments, instead just call the byte-code
2870 interpreter directly; it will push arguments as necessary.
2872 Byte-code objects with either a non-existent, or a nil value for
2873 the `push args' slot (the default), have dynamically-bound
2874 arguments, and use the argument-binding code below instead (as do
2875 all interpreted functions, even lexically bound ones). */
2877 /* If we have not actually read the bytecode string
2878 and constants vector yet, fetch them from the file. */
2879 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2880 Ffetch_bytecode (fun);
2881 return exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2882 AREF (fun, COMPILED_CONSTANTS),
2883 AREF (fun, COMPILED_STACK_DEPTH),
2884 syms_left,
2885 nargs, arg_vector);
2887 lexenv = Qnil;
2889 else
2890 emacs_abort ();
2892 i = optional = rest = 0;
2893 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
2895 QUIT;
2897 next = XCAR (syms_left);
2898 if (!SYMBOLP (next))
2899 xsignal1 (Qinvalid_function, fun);
2901 if (EQ (next, Qand_rest))
2902 rest = 1;
2903 else if (EQ (next, Qand_optional))
2904 optional = 1;
2905 else
2907 Lisp_Object arg;
2908 if (rest)
2910 arg = Flist (nargs - i, &arg_vector[i]);
2911 i = nargs;
2913 else if (i < nargs)
2914 arg = arg_vector[i++];
2915 else if (!optional)
2916 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2917 else
2918 arg = Qnil;
2920 /* Bind the argument. */
2921 if (!NILP (lexenv) && SYMBOLP (next))
2922 /* Lexically bind NEXT by adding it to the lexenv alist. */
2923 lexenv = Fcons (Fcons (next, arg), lexenv);
2924 else
2925 /* Dynamically bind NEXT. */
2926 specbind (next, arg);
2930 if (!NILP (syms_left))
2931 xsignal1 (Qinvalid_function, fun);
2932 else if (i < nargs)
2933 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2935 if (!EQ (lexenv, Vinternal_interpreter_environment))
2936 /* Instantiate a new lexical environment. */
2937 specbind (Qinternal_interpreter_environment, lexenv);
2939 if (CONSP (fun))
2940 val = Fprogn (XCDR (XCDR (fun)));
2941 else
2943 /* If we have not actually read the bytecode string
2944 and constants vector yet, fetch them from the file. */
2945 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2946 Ffetch_bytecode (fun);
2947 val = exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2948 AREF (fun, COMPILED_CONSTANTS),
2949 AREF (fun, COMPILED_STACK_DEPTH),
2950 Qnil, 0, 0);
2953 return unbind_to (count, val);
2956 DEFUN ("fetch-bytecode", Ffetch_bytecode, Sfetch_bytecode,
2957 1, 1, 0,
2958 doc: /* If byte-compiled OBJECT is lazy-loaded, fetch it now. */)
2959 (Lisp_Object object)
2961 Lisp_Object tem;
2963 if (COMPILEDP (object) && CONSP (AREF (object, COMPILED_BYTECODE)))
2965 tem = read_doc_string (AREF (object, COMPILED_BYTECODE));
2966 if (!CONSP (tem))
2968 tem = AREF (object, COMPILED_BYTECODE);
2969 if (CONSP (tem) && STRINGP (XCAR (tem)))
2970 error ("Invalid byte code in %s", SDATA (XCAR (tem)));
2971 else
2972 error ("Invalid byte code");
2974 ASET (object, COMPILED_BYTECODE, XCAR (tem));
2975 ASET (object, COMPILED_CONSTANTS, XCDR (tem));
2977 return object;
2980 /* Return true if SYMBOL currently has a let-binding
2981 which was made in the buffer that is now current. */
2983 bool
2984 let_shadows_buffer_binding_p (struct Lisp_Symbol *symbol)
2986 union specbinding *p;
2987 Lisp_Object buf = Fcurrent_buffer ();
2989 for (p = specpdl_ptr; p > specpdl; )
2990 if ((--p)->kind > SPECPDL_LET)
2992 struct Lisp_Symbol *let_bound_symbol = XSYMBOL (specpdl_symbol (p));
2993 eassert (let_bound_symbol->redirect != SYMBOL_VARALIAS);
2994 if (symbol == let_bound_symbol
2995 && EQ (specpdl_where (p), buf))
2996 return 1;
2999 return 0;
3002 bool
3003 let_shadows_global_binding_p (Lisp_Object symbol)
3005 union specbinding *p;
3007 for (p = specpdl_ptr; p > specpdl; )
3008 if ((--p)->kind >= SPECPDL_LET && EQ (specpdl_symbol (p), symbol))
3009 return 1;
3011 return 0;
3014 /* `specpdl_ptr' describes which variable is
3015 let-bound, so it can be properly undone when we unbind_to.
3016 It can be either a plain SPECPDL_LET or a SPECPDL_LET_LOCAL/DEFAULT.
3017 - SYMBOL is the variable being bound. Note that it should not be
3018 aliased (i.e. when let-binding V1 that's aliased to V2, we want
3019 to record V2 here).
3020 - WHERE tells us in which buffer the binding took place.
3021 This is used for SPECPDL_LET_LOCAL bindings (i.e. bindings to a
3022 buffer-local variable) as well as for SPECPDL_LET_DEFAULT bindings,
3023 i.e. bindings to the default value of a variable which can be
3024 buffer-local. */
3026 void
3027 specbind (Lisp_Object symbol, Lisp_Object value)
3029 struct Lisp_Symbol *sym;
3031 CHECK_SYMBOL (symbol);
3032 sym = XSYMBOL (symbol);
3034 start:
3035 switch (sym->redirect)
3037 case SYMBOL_VARALIAS:
3038 sym = indirect_variable (sym); XSETSYMBOL (symbol, sym); goto start;
3039 case SYMBOL_PLAINVAL:
3040 /* The most common case is that of a non-constant symbol with a
3041 trivial value. Make that as fast as we can. */
3042 specpdl_ptr->let.kind = SPECPDL_LET;
3043 specpdl_ptr->let.symbol = symbol;
3044 specpdl_ptr->let.old_value = SYMBOL_VAL (sym);
3045 grow_specpdl ();
3046 if (!sym->constant)
3047 SET_SYMBOL_VAL (sym, value);
3048 else
3049 set_internal (symbol, value, Qnil, 1);
3050 break;
3051 case SYMBOL_LOCALIZED:
3052 if (SYMBOL_BLV (sym)->frame_local)
3053 error ("Frame-local vars cannot be let-bound");
3054 case SYMBOL_FORWARDED:
3056 Lisp_Object ovalue = find_symbol_value (symbol);
3057 specpdl_ptr->let.kind = SPECPDL_LET_LOCAL;
3058 specpdl_ptr->let.symbol = symbol;
3059 specpdl_ptr->let.old_value = ovalue;
3060 specpdl_ptr->let.where = Fcurrent_buffer ();
3062 eassert (sym->redirect != SYMBOL_LOCALIZED
3063 || (EQ (SYMBOL_BLV (sym)->where, Fcurrent_buffer ())));
3065 if (sym->redirect == SYMBOL_LOCALIZED)
3067 if (!blv_found (SYMBOL_BLV (sym)))
3068 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3070 else if (BUFFER_OBJFWDP (SYMBOL_FWD (sym)))
3072 /* If SYMBOL is a per-buffer variable which doesn't have a
3073 buffer-local value here, make the `let' change the global
3074 value by changing the value of SYMBOL in all buffers not
3075 having their own value. This is consistent with what
3076 happens with other buffer-local variables. */
3077 if (NILP (Flocal_variable_p (symbol, Qnil)))
3079 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3080 grow_specpdl ();
3081 Fset_default (symbol, value);
3082 return;
3085 else
3086 specpdl_ptr->let.kind = SPECPDL_LET;
3088 grow_specpdl ();
3089 set_internal (symbol, value, Qnil, 1);
3090 break;
3092 default: emacs_abort ();
3096 /* Push unwind-protect entries of various types. */
3098 void
3099 record_unwind_protect (void (*function) (Lisp_Object), Lisp_Object arg)
3101 specpdl_ptr->unwind.kind = SPECPDL_UNWIND;
3102 specpdl_ptr->unwind.func = function;
3103 specpdl_ptr->unwind.arg = arg;
3104 grow_specpdl ();
3107 void
3108 record_unwind_protect_ptr (void (*function) (void *), void *arg)
3110 specpdl_ptr->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3111 specpdl_ptr->unwind_ptr.func = function;
3112 specpdl_ptr->unwind_ptr.arg = arg;
3113 grow_specpdl ();
3116 void
3117 record_unwind_protect_int (void (*function) (int), int arg)
3119 specpdl_ptr->unwind_int.kind = SPECPDL_UNWIND_INT;
3120 specpdl_ptr->unwind_int.func = function;
3121 specpdl_ptr->unwind_int.arg = arg;
3122 grow_specpdl ();
3125 void
3126 record_unwind_protect_void (void (*function) (void))
3128 specpdl_ptr->unwind_void.kind = SPECPDL_UNWIND_VOID;
3129 specpdl_ptr->unwind_void.func = function;
3130 grow_specpdl ();
3133 static void
3134 do_nothing (void)
3137 /* Push an unwind-protect entry that does nothing, so that
3138 set_unwind_protect_ptr can overwrite it later. */
3140 void
3141 record_unwind_protect_nothing (void)
3143 record_unwind_protect_void (do_nothing);
3146 /* Clear the unwind-protect entry COUNT, so that it does nothing.
3147 It need not be at the top of the stack. */
3149 void
3150 clear_unwind_protect (ptrdiff_t count)
3152 union specbinding *p = specpdl + count;
3153 p->unwind_void.kind = SPECPDL_UNWIND_VOID;
3154 p->unwind_void.func = do_nothing;
3157 /* Set the unwind-protect entry COUNT so that it invokes FUNC (ARG).
3158 It need not be at the top of the stack. Discard the entry's
3159 previous value without invoking it. */
3161 void
3162 set_unwind_protect (ptrdiff_t count, void (*func) (Lisp_Object),
3163 Lisp_Object arg)
3165 union specbinding *p = specpdl + count;
3166 p->unwind.kind = SPECPDL_UNWIND;
3167 p->unwind.func = func;
3168 p->unwind.arg = arg;
3171 void
3172 set_unwind_protect_ptr (ptrdiff_t count, void (*func) (void *), void *arg)
3174 union specbinding *p = specpdl + count;
3175 p->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3176 p->unwind_ptr.func = func;
3177 p->unwind_ptr.arg = arg;
3180 /* Pop and execute entries from the unwind-protect stack until the
3181 depth COUNT is reached. Return VALUE. */
3183 Lisp_Object
3184 unbind_to (ptrdiff_t count, Lisp_Object value)
3186 Lisp_Object quitf = Vquit_flag;
3187 struct gcpro gcpro1, gcpro2;
3189 GCPRO2 (value, quitf);
3190 Vquit_flag = Qnil;
3192 while (specpdl_ptr != specpdl + count)
3194 /* Decrement specpdl_ptr before we do the work to unbind it, so
3195 that an error in unbinding won't try to unbind the same entry
3196 again. Take care to copy any parts of the binding needed
3197 before invoking any code that can make more bindings. */
3199 specpdl_ptr--;
3201 switch (specpdl_ptr->kind)
3203 case SPECPDL_UNWIND:
3204 specpdl_ptr->unwind.func (specpdl_ptr->unwind.arg);
3205 break;
3206 case SPECPDL_UNWIND_PTR:
3207 specpdl_ptr->unwind_ptr.func (specpdl_ptr->unwind_ptr.arg);
3208 break;
3209 case SPECPDL_UNWIND_INT:
3210 specpdl_ptr->unwind_int.func (specpdl_ptr->unwind_int.arg);
3211 break;
3212 case SPECPDL_UNWIND_VOID:
3213 specpdl_ptr->unwind_void.func ();
3214 break;
3215 case SPECPDL_BACKTRACE:
3216 break;
3217 case SPECPDL_LET:
3218 { /* If variable has a trivial value (no forwarding), we can
3219 just set it. No need to check for constant symbols here,
3220 since that was already done by specbind. */
3221 struct Lisp_Symbol *sym = XSYMBOL (specpdl_symbol (specpdl_ptr));
3222 if (sym->redirect == SYMBOL_PLAINVAL)
3224 SET_SYMBOL_VAL (sym, specpdl_old_value (specpdl_ptr));
3225 break;
3227 else
3228 { /* FALLTHROUGH!!
3229 NOTE: we only ever come here if make_local_foo was used for
3230 the first time on this var within this let. */
3233 case SPECPDL_LET_DEFAULT:
3234 Fset_default (specpdl_symbol (specpdl_ptr),
3235 specpdl_old_value (specpdl_ptr));
3236 break;
3237 case SPECPDL_LET_LOCAL:
3239 Lisp_Object symbol = specpdl_symbol (specpdl_ptr);
3240 Lisp_Object where = specpdl_where (specpdl_ptr);
3241 Lisp_Object old_value = specpdl_old_value (specpdl_ptr);
3242 eassert (BUFFERP (where));
3244 /* If this was a local binding, reset the value in the appropriate
3245 buffer, but only if that buffer's binding still exists. */
3246 if (!NILP (Flocal_variable_p (symbol, where)))
3247 set_internal (symbol, old_value, where, 1);
3249 break;
3253 if (NILP (Vquit_flag) && !NILP (quitf))
3254 Vquit_flag = quitf;
3256 UNGCPRO;
3257 return value;
3260 DEFUN ("special-variable-p", Fspecial_variable_p, Sspecial_variable_p, 1, 1, 0,
3261 doc: /* Return non-nil if SYMBOL's global binding has been declared special.
3262 A special variable is one that will be bound dynamically, even in a
3263 context where binding is lexical by default. */)
3264 (Lisp_Object symbol)
3266 CHECK_SYMBOL (symbol);
3267 return XSYMBOL (symbol)->declared_special ? Qt : Qnil;
3271 DEFUN ("backtrace-debug", Fbacktrace_debug, Sbacktrace_debug, 2, 2, 0,
3272 doc: /* Set the debug-on-exit flag of eval frame LEVEL levels down to FLAG.
3273 The debugger is entered when that frame exits, if the flag is non-nil. */)
3274 (Lisp_Object level, Lisp_Object flag)
3276 union specbinding *pdl = backtrace_top ();
3277 register EMACS_INT i;
3279 CHECK_NUMBER (level);
3281 for (i = 0; backtrace_p (pdl) && i < XINT (level); i++)
3282 pdl = backtrace_next (pdl);
3284 if (backtrace_p (pdl))
3285 set_backtrace_debug_on_exit (pdl, !NILP (flag));
3287 return flag;
3290 DEFUN ("backtrace", Fbacktrace, Sbacktrace, 0, 0, "",
3291 doc: /* Print a trace of Lisp function calls currently active.
3292 Output stream used is value of `standard-output'. */)
3293 (void)
3295 union specbinding *pdl = backtrace_top ();
3296 Lisp_Object tem;
3297 Lisp_Object old_print_level = Vprint_level;
3299 if (NILP (Vprint_level))
3300 XSETFASTINT (Vprint_level, 8);
3302 while (backtrace_p (pdl))
3304 write_string (backtrace_debug_on_exit (pdl) ? "* " : " ", 2);
3305 if (backtrace_nargs (pdl) == UNEVALLED)
3307 Fprin1 (Fcons (backtrace_function (pdl), *backtrace_args (pdl)),
3308 Qnil);
3309 write_string ("\n", -1);
3311 else
3313 tem = backtrace_function (pdl);
3314 Fprin1 (tem, Qnil); /* This can QUIT. */
3315 write_string ("(", -1);
3317 ptrdiff_t i;
3318 for (i = 0; i < backtrace_nargs (pdl); i++)
3320 if (i) write_string (" ", -1);
3321 Fprin1 (backtrace_args (pdl)[i], Qnil);
3324 write_string (")\n", -1);
3326 pdl = backtrace_next (pdl);
3329 Vprint_level = old_print_level;
3330 return Qnil;
3333 static union specbinding *
3334 get_backtrace_frame (Lisp_Object nframes, Lisp_Object base)
3336 union specbinding *pdl = backtrace_top ();
3337 register EMACS_INT i;
3339 CHECK_NATNUM (nframes);
3341 if (!NILP (base))
3342 { /* Skip up to `base'. */
3343 base = Findirect_function (base, Qt);
3344 while (backtrace_p (pdl)
3345 && !EQ (base, Findirect_function (backtrace_function (pdl), Qt)))
3346 pdl = backtrace_next (pdl);
3349 /* Find the frame requested. */
3350 for (i = XFASTINT (nframes); i > 0 && backtrace_p (pdl); i--)
3351 pdl = backtrace_next (pdl);
3353 return pdl;
3356 DEFUN ("backtrace-frame", Fbacktrace_frame, Sbacktrace_frame, 1, 2, NULL,
3357 doc: /* Return the function and arguments NFRAMES up from current execution point.
3358 If that frame has not evaluated the arguments yet (or is a special form),
3359 the value is (nil FUNCTION ARG-FORMS...).
3360 If that frame has evaluated its arguments and called its function already,
3361 the value is (t FUNCTION ARG-VALUES...).
3362 A &rest arg is represented as the tail of the list ARG-VALUES.
3363 FUNCTION is whatever was supplied as car of evaluated list,
3364 or a lambda expression for macro calls.
3365 If NFRAMES is more than the number of frames, the value is nil.
3366 If BASE is non-nil, it should be a function and NFRAMES counts from its
3367 nearest activation frame. */)
3368 (Lisp_Object nframes, Lisp_Object base)
3370 union specbinding *pdl = get_backtrace_frame (nframes, base);
3372 if (!backtrace_p (pdl))
3373 return Qnil;
3374 if (backtrace_nargs (pdl) == UNEVALLED)
3375 return Fcons (Qnil,
3376 Fcons (backtrace_function (pdl), *backtrace_args (pdl)));
3377 else
3379 Lisp_Object tem = Flist (backtrace_nargs (pdl), backtrace_args (pdl));
3381 return Fcons (Qt, Fcons (backtrace_function (pdl), tem));
3385 /* For backtrace-eval, we want to temporarily unwind the last few elements of
3386 the specpdl stack, and then rewind them. We store the pre-unwind values
3387 directly in the pre-existing specpdl elements (i.e. we swap the current
3388 value and the old value stored in the specpdl), kind of like the inplace
3389 pointer-reversal trick. As it turns out, the rewind does the same as the
3390 unwind, except it starts from the other end of the specpdl stack, so we use
3391 the same function for both unwind and rewind. */
3392 static void
3393 backtrace_eval_unrewind (int distance)
3395 union specbinding *tmp = specpdl_ptr;
3396 int step = -1;
3397 if (distance < 0)
3398 { /* It's a rewind rather than unwind. */
3399 tmp += distance - 1;
3400 step = 1;
3401 distance = -distance;
3404 for (; distance > 0; distance--)
3406 tmp += step;
3407 switch (tmp->kind)
3409 /* FIXME: Ideally we'd like to "temporarily unwind" (some of) those
3410 unwind_protect, but the problem is that we don't know how to
3411 rewind them afterwards. */
3412 case SPECPDL_UNWIND:
3414 Lisp_Object oldarg = tmp->unwind.arg;
3415 if (tmp->unwind.func == set_buffer_if_live)
3416 tmp->unwind.arg = Fcurrent_buffer ();
3417 else if (tmp->unwind.func == save_excursion_restore)
3418 tmp->unwind.arg = save_excursion_save ();
3419 else
3420 break;
3421 tmp->unwind.func (oldarg);
3422 break;
3425 case SPECPDL_UNWIND_PTR:
3426 case SPECPDL_UNWIND_INT:
3427 case SPECPDL_UNWIND_VOID:
3428 case SPECPDL_BACKTRACE:
3429 break;
3430 case SPECPDL_LET:
3431 { /* If variable has a trivial value (no forwarding), we can
3432 just set it. No need to check for constant symbols here,
3433 since that was already done by specbind. */
3434 struct Lisp_Symbol *sym = XSYMBOL (specpdl_symbol (tmp));
3435 if (sym->redirect == SYMBOL_PLAINVAL)
3437 Lisp_Object old_value = specpdl_old_value (tmp);
3438 set_specpdl_old_value (tmp, SYMBOL_VAL (sym));
3439 SET_SYMBOL_VAL (sym, old_value);
3440 break;
3442 else
3443 { /* FALLTHROUGH!!
3444 NOTE: we only ever come here if make_local_foo was used for
3445 the first time on this var within this let. */
3448 case SPECPDL_LET_DEFAULT:
3450 Lisp_Object sym = specpdl_symbol (tmp);
3451 Lisp_Object old_value = specpdl_old_value (tmp);
3452 set_specpdl_old_value (tmp, Fdefault_value (sym));
3453 Fset_default (sym, old_value);
3455 break;
3456 case SPECPDL_LET_LOCAL:
3458 Lisp_Object symbol = specpdl_symbol (tmp);
3459 Lisp_Object where = specpdl_where (tmp);
3460 Lisp_Object old_value = specpdl_old_value (tmp);
3461 eassert (BUFFERP (where));
3463 /* If this was a local binding, reset the value in the appropriate
3464 buffer, but only if that buffer's binding still exists. */
3465 if (!NILP (Flocal_variable_p (symbol, where)))
3467 set_specpdl_old_value
3468 (tmp, Fbuffer_local_value (symbol, where));
3469 set_internal (symbol, old_value, where, 1);
3472 break;
3477 DEFUN ("backtrace-eval", Fbacktrace_eval, Sbacktrace_eval, 2, 3, NULL,
3478 doc: /* Evaluate EXP in the context of some activation frame.
3479 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3480 (Lisp_Object exp, Lisp_Object nframes, Lisp_Object base)
3482 union specbinding *pdl = get_backtrace_frame (nframes, base);
3483 ptrdiff_t count = SPECPDL_INDEX ();
3484 ptrdiff_t distance = specpdl_ptr - pdl;
3485 eassert (distance >= 0);
3487 if (!backtrace_p (pdl))
3488 error ("Activation frame not found!");
3490 backtrace_eval_unrewind (distance);
3491 record_unwind_protect_int (backtrace_eval_unrewind, -distance);
3493 /* Use eval_sub rather than Feval since the main motivation behind
3494 backtrace-eval is to be able to get/set the value of lexical variables
3495 from the debugger. */
3496 return unbind_to (count, eval_sub (exp));
3499 DEFUN ("backtrace--locals", Fbacktrace__locals, Sbacktrace__locals, 1, 2, NULL,
3500 doc: /* Return names and values of local variables of a stack frame.
3501 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3502 (Lisp_Object nframes, Lisp_Object base)
3504 union specbinding *frame = get_backtrace_frame (nframes, base);
3505 union specbinding *prevframe
3506 = get_backtrace_frame (make_number (XFASTINT (nframes) - 1), base);
3507 ptrdiff_t distance = specpdl_ptr - frame;
3508 Lisp_Object result = Qnil;
3509 eassert (distance >= 0);
3511 if (!backtrace_p (prevframe))
3512 error ("Activation frame not found!");
3513 if (!backtrace_p (frame))
3514 error ("Activation frame not found!");
3516 /* The specpdl entries normally contain the symbol being bound along with its
3517 `old_value', so it can be restored. The new value to which it is bound is
3518 available in one of two places: either in the current value of the
3519 variable (if it hasn't been rebound yet) or in the `old_value' slot of the
3520 next specpdl entry for it.
3521 `backtrace_eval_unrewind' happens to swap the role of `old_value'
3522 and "new value", so we abuse it here, to fetch the new value.
3523 It's ugly (we'd rather not modify global data) and a bit inefficient,
3524 but it does the job for now. */
3525 backtrace_eval_unrewind (distance);
3527 /* Grab values. */
3529 union specbinding *tmp = prevframe;
3530 for (; tmp > frame; tmp--)
3532 switch (tmp->kind)
3534 case SPECPDL_LET:
3535 case SPECPDL_LET_DEFAULT:
3536 case SPECPDL_LET_LOCAL:
3538 Lisp_Object sym = specpdl_symbol (tmp);
3539 Lisp_Object val = specpdl_old_value (tmp);
3540 if (EQ (sym, Qinternal_interpreter_environment))
3542 Lisp_Object env = val;
3543 for (; CONSP (env); env = XCDR (env))
3545 Lisp_Object binding = XCAR (env);
3546 if (CONSP (binding))
3547 result = Fcons (Fcons (XCAR (binding),
3548 XCDR (binding)),
3549 result);
3552 else
3553 result = Fcons (Fcons (sym, val), result);
3559 /* Restore values from specpdl to original place. */
3560 backtrace_eval_unrewind (-distance);
3562 return result;
3566 void
3567 mark_specpdl (void)
3569 union specbinding *pdl;
3570 for (pdl = specpdl; pdl != specpdl_ptr; pdl++)
3572 switch (pdl->kind)
3574 case SPECPDL_UNWIND:
3575 mark_object (specpdl_arg (pdl));
3576 break;
3578 case SPECPDL_BACKTRACE:
3580 ptrdiff_t nargs = backtrace_nargs (pdl);
3581 mark_object (backtrace_function (pdl));
3582 if (nargs == UNEVALLED)
3583 nargs = 1;
3584 while (nargs--)
3585 mark_object (backtrace_args (pdl)[nargs]);
3587 break;
3589 case SPECPDL_LET_DEFAULT:
3590 case SPECPDL_LET_LOCAL:
3591 mark_object (specpdl_where (pdl));
3592 /* Fall through. */
3593 case SPECPDL_LET:
3594 mark_object (specpdl_symbol (pdl));
3595 mark_object (specpdl_old_value (pdl));
3596 break;
3601 void
3602 get_backtrace (Lisp_Object array)
3604 union specbinding *pdl = backtrace_next (backtrace_top ());
3605 ptrdiff_t i = 0, asize = ASIZE (array);
3607 /* Copy the backtrace contents into working memory. */
3608 for (; i < asize; i++)
3610 if (backtrace_p (pdl))
3612 ASET (array, i, backtrace_function (pdl));
3613 pdl = backtrace_next (pdl);
3615 else
3616 ASET (array, i, Qnil);
3620 Lisp_Object backtrace_top_function (void)
3622 union specbinding *pdl = backtrace_top ();
3623 return (backtrace_p (pdl) ? backtrace_function (pdl) : Qnil);
3626 void
3627 syms_of_eval (void)
3629 DEFVAR_INT ("max-specpdl-size", max_specpdl_size,
3630 doc: /* Limit on number of Lisp variable bindings and `unwind-protect's.
3631 If Lisp code tries to increase the total number past this amount,
3632 an error is signaled.
3633 You can safely use a value considerably larger than the default value,
3634 if that proves inconveniently small. However, if you increase it too far,
3635 Emacs could run out of memory trying to make the stack bigger.
3636 Note that this limit may be silently increased by the debugger
3637 if `debug-on-error' or `debug-on-quit' is set. */);
3639 DEFVAR_INT ("max-lisp-eval-depth", max_lisp_eval_depth,
3640 doc: /* Limit on depth in `eval', `apply' and `funcall' before error.
3642 This limit serves to catch infinite recursions for you before they cause
3643 actual stack overflow in C, which would be fatal for Emacs.
3644 You can safely make it considerably larger than its default value,
3645 if that proves inconveniently small. However, if you increase it too far,
3646 Emacs could overflow the real C stack, and crash. */);
3648 DEFVAR_LISP ("quit-flag", Vquit_flag,
3649 doc: /* Non-nil causes `eval' to abort, unless `inhibit-quit' is non-nil.
3650 If the value is t, that means do an ordinary quit.
3651 If the value equals `throw-on-input', that means quit by throwing
3652 to the tag specified in `throw-on-input'; it's for handling `while-no-input'.
3653 Typing C-g sets `quit-flag' to t, regardless of `inhibit-quit',
3654 but `inhibit-quit' non-nil prevents anything from taking notice of that. */);
3655 Vquit_flag = Qnil;
3657 DEFVAR_LISP ("inhibit-quit", Vinhibit_quit,
3658 doc: /* Non-nil inhibits C-g quitting from happening immediately.
3659 Note that `quit-flag' will still be set by typing C-g,
3660 so a quit will be signaled as soon as `inhibit-quit' is nil.
3661 To prevent this happening, set `quit-flag' to nil
3662 before making `inhibit-quit' nil. */);
3663 Vinhibit_quit = Qnil;
3665 DEFSYM (Qinhibit_quit, "inhibit-quit");
3666 DEFSYM (Qautoload, "autoload");
3667 DEFSYM (Qinhibit_debugger, "inhibit-debugger");
3668 DEFSYM (Qmacro, "macro");
3669 DEFSYM (Qdeclare, "declare");
3671 /* Note that the process handling also uses Qexit, but we don't want
3672 to staticpro it twice, so we just do it here. */
3673 DEFSYM (Qexit, "exit");
3675 DEFSYM (Qinteractive, "interactive");
3676 DEFSYM (Qcommandp, "commandp");
3677 DEFSYM (Qand_rest, "&rest");
3678 DEFSYM (Qand_optional, "&optional");
3679 DEFSYM (Qclosure, "closure");
3680 DEFSYM (Qdebug, "debug");
3682 DEFVAR_LISP ("inhibit-debugger", Vinhibit_debugger,
3683 doc: /* Non-nil means never enter the debugger.
3684 Normally set while the debugger is already active, to avoid recursive
3685 invocations. */);
3686 Vinhibit_debugger = Qnil;
3688 DEFVAR_LISP ("debug-on-error", Vdebug_on_error,
3689 doc: /* Non-nil means enter debugger if an error is signaled.
3690 Does not apply to errors handled by `condition-case' or those
3691 matched by `debug-ignored-errors'.
3692 If the value is a list, an error only means to enter the debugger
3693 if one of its condition symbols appears in the list.
3694 When you evaluate an expression interactively, this variable
3695 is temporarily non-nil if `eval-expression-debug-on-error' is non-nil.
3696 The command `toggle-debug-on-error' toggles this.
3697 See also the variable `debug-on-quit' and `inhibit-debugger'. */);
3698 Vdebug_on_error = Qnil;
3700 DEFVAR_LISP ("debug-ignored-errors", Vdebug_ignored_errors,
3701 doc: /* List of errors for which the debugger should not be called.
3702 Each element may be a condition-name or a regexp that matches error messages.
3703 If any element applies to a given error, that error skips the debugger
3704 and just returns to top level.
3705 This overrides the variable `debug-on-error'.
3706 It does not apply to errors handled by `condition-case'. */);
3707 Vdebug_ignored_errors = Qnil;
3709 DEFVAR_BOOL ("debug-on-quit", debug_on_quit,
3710 doc: /* Non-nil means enter debugger if quit is signaled (C-g, for example).
3711 Does not apply if quit is handled by a `condition-case'. */);
3712 debug_on_quit = 0;
3714 DEFVAR_BOOL ("debug-on-next-call", debug_on_next_call,
3715 doc: /* Non-nil means enter debugger before next `eval', `apply' or `funcall'. */);
3717 DEFVAR_BOOL ("debugger-may-continue", debugger_may_continue,
3718 doc: /* Non-nil means debugger may continue execution.
3719 This is nil when the debugger is called under circumstances where it
3720 might not be safe to continue. */);
3721 debugger_may_continue = 1;
3723 DEFVAR_LISP ("debugger", Vdebugger,
3724 doc: /* Function to call to invoke debugger.
3725 If due to frame exit, args are `exit' and the value being returned;
3726 this function's value will be returned instead of that.
3727 If due to error, args are `error' and a list of the args to `signal'.
3728 If due to `apply' or `funcall' entry, one arg, `lambda'.
3729 If due to `eval' entry, one arg, t. */);
3730 Vdebugger = Qnil;
3732 DEFVAR_LISP ("signal-hook-function", Vsignal_hook_function,
3733 doc: /* If non-nil, this is a function for `signal' to call.
3734 It receives the same arguments that `signal' was given.
3735 The Edebug package uses this to regain control. */);
3736 Vsignal_hook_function = Qnil;
3738 DEFVAR_LISP ("debug-on-signal", Vdebug_on_signal,
3739 doc: /* Non-nil means call the debugger regardless of condition handlers.
3740 Note that `debug-on-error', `debug-on-quit' and friends
3741 still determine whether to handle the particular condition. */);
3742 Vdebug_on_signal = Qnil;
3744 /* When lexical binding is being used,
3745 Vinternal_interpreter_environment is non-nil, and contains an alist
3746 of lexically-bound variable, or (t), indicating an empty
3747 environment. The lisp name of this variable would be
3748 `internal-interpreter-environment' if it weren't hidden.
3749 Every element of this list can be either a cons (VAR . VAL)
3750 specifying a lexical binding, or a single symbol VAR indicating
3751 that this variable should use dynamic scoping. */
3752 DEFSYM (Qinternal_interpreter_environment,
3753 "internal-interpreter-environment");
3754 DEFVAR_LISP ("internal-interpreter-environment",
3755 Vinternal_interpreter_environment,
3756 doc: /* If non-nil, the current lexical environment of the lisp interpreter.
3757 When lexical binding is not being used, this variable is nil.
3758 A value of `(t)' indicates an empty environment, otherwise it is an
3759 alist of active lexical bindings. */);
3760 Vinternal_interpreter_environment = Qnil;
3761 /* Don't export this variable to Elisp, so no one can mess with it
3762 (Just imagine if someone makes it buffer-local). */
3763 Funintern (Qinternal_interpreter_environment, Qnil);
3765 DEFSYM (Vrun_hooks, "run-hooks");
3767 staticpro (&Vautoload_queue);
3768 Vautoload_queue = Qnil;
3769 staticpro (&Vsignaling_function);
3770 Vsignaling_function = Qnil;
3772 inhibit_lisp_code = Qnil;
3774 defsubr (&Sor);
3775 defsubr (&Sand);
3776 defsubr (&Sif);
3777 defsubr (&Scond);
3778 defsubr (&Sprogn);
3779 defsubr (&Sprog1);
3780 defsubr (&Sprog2);
3781 defsubr (&Ssetq);
3782 defsubr (&Squote);
3783 defsubr (&Sfunction);
3784 defsubr (&Sdefault_toplevel_value);
3785 defsubr (&Sset_default_toplevel_value);
3786 defsubr (&Sdefvar);
3787 defsubr (&Sdefvaralias);
3788 defsubr (&Sdefconst);
3789 defsubr (&Smake_var_non_special);
3790 defsubr (&Slet);
3791 defsubr (&SletX);
3792 defsubr (&Swhile);
3793 defsubr (&Smacroexpand);
3794 defsubr (&Scatch);
3795 defsubr (&Sthrow);
3796 defsubr (&Sunwind_protect);
3797 defsubr (&Scondition_case);
3798 defsubr (&Ssignal);
3799 defsubr (&Scommandp);
3800 defsubr (&Sautoload);
3801 defsubr (&Sautoload_do_load);
3802 defsubr (&Seval);
3803 defsubr (&Sapply);
3804 defsubr (&Sfuncall);
3805 defsubr (&Srun_hooks);
3806 defsubr (&Srun_hook_with_args);
3807 defsubr (&Srun_hook_with_args_until_success);
3808 defsubr (&Srun_hook_with_args_until_failure);
3809 defsubr (&Srun_hook_wrapped);
3810 defsubr (&Sfetch_bytecode);
3811 defsubr (&Sbacktrace_debug);
3812 defsubr (&Sbacktrace);
3813 defsubr (&Sbacktrace_frame);
3814 defsubr (&Sbacktrace_eval);
3815 defsubr (&Sbacktrace__locals);
3816 defsubr (&Sspecial_variable_p);
3817 defsubr (&Sfunctionp);