Merge from emacs-24
[emacs.git] / src / eval.c
blob8a83fdb78803443fc01b93fb6654652e29ba85ef
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) && CONSP (clause)
1537 && !NILP (Fmemq (Qdebug, clause)))
1538 /* Special handler that means "print a message and run debugger
1539 if requested". */
1540 || EQ (h->tag_or_ch, Qerror)))
1542 bool debugger_called
1543 = maybe_call_debugger (conditions, error_symbol, data);
1544 /* We can't return values to code which signaled an error, but we
1545 can continue code which has signaled a quit. */
1546 if (debugger_called && EQ (real_error_symbol, Qquit))
1547 return Qnil;
1550 if (!NILP (clause))
1552 Lisp_Object unwind_data
1553 = (NILP (error_symbol) ? data : Fcons (error_symbol, data));
1555 unwind_to_catch (h, unwind_data);
1557 else
1559 if (handlerlist != &handlerlist_sentinel)
1560 /* FIXME: This will come right back here if there's no `top-level'
1561 catcher. A better solution would be to abort here, and instead
1562 add a catch-all condition handler so we never come here. */
1563 Fthrow (Qtop_level, Qt);
1566 if (! NILP (error_symbol))
1567 data = Fcons (error_symbol, data);
1569 string = Ferror_message_string (data);
1570 fatal ("%s", SDATA (string));
1573 /* Internal version of Fsignal that never returns.
1574 Used for anything but Qquit (which can return from Fsignal). */
1576 void
1577 xsignal (Lisp_Object error_symbol, Lisp_Object data)
1579 Fsignal (error_symbol, data);
1580 emacs_abort ();
1583 /* Like xsignal, but takes 0, 1, 2, or 3 args instead of a list. */
1585 void
1586 xsignal0 (Lisp_Object error_symbol)
1588 xsignal (error_symbol, Qnil);
1591 void
1592 xsignal1 (Lisp_Object error_symbol, Lisp_Object arg)
1594 xsignal (error_symbol, list1 (arg));
1597 void
1598 xsignal2 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2)
1600 xsignal (error_symbol, list2 (arg1, arg2));
1603 void
1604 xsignal3 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
1606 xsignal (error_symbol, list3 (arg1, arg2, arg3));
1609 /* Signal `error' with message S, and additional arg ARG.
1610 If ARG is not a genuine list, make it a one-element list. */
1612 void
1613 signal_error (const char *s, Lisp_Object arg)
1615 Lisp_Object tortoise, hare;
1617 hare = tortoise = arg;
1618 while (CONSP (hare))
1620 hare = XCDR (hare);
1621 if (!CONSP (hare))
1622 break;
1624 hare = XCDR (hare);
1625 tortoise = XCDR (tortoise);
1627 if (EQ (hare, tortoise))
1628 break;
1631 if (!NILP (hare))
1632 arg = list1 (arg);
1634 xsignal (Qerror, Fcons (build_string (s), arg));
1638 /* Return true if LIST is a non-nil atom or
1639 a list containing one of CONDITIONS. */
1641 static bool
1642 wants_debugger (Lisp_Object list, Lisp_Object conditions)
1644 if (NILP (list))
1645 return 0;
1646 if (! CONSP (list))
1647 return 1;
1649 while (CONSP (conditions))
1651 Lisp_Object this, tail;
1652 this = XCAR (conditions);
1653 for (tail = list; CONSP (tail); tail = XCDR (tail))
1654 if (EQ (XCAR (tail), this))
1655 return 1;
1656 conditions = XCDR (conditions);
1658 return 0;
1661 /* Return true if an error with condition-symbols CONDITIONS,
1662 and described by SIGNAL-DATA, should skip the debugger
1663 according to debugger-ignored-errors. */
1665 static bool
1666 skip_debugger (Lisp_Object conditions, Lisp_Object data)
1668 Lisp_Object tail;
1669 bool first_string = 1;
1670 Lisp_Object error_message;
1672 error_message = Qnil;
1673 for (tail = Vdebug_ignored_errors; CONSP (tail); tail = XCDR (tail))
1675 if (STRINGP (XCAR (tail)))
1677 if (first_string)
1679 error_message = Ferror_message_string (data);
1680 first_string = 0;
1683 if (fast_string_match (XCAR (tail), error_message) >= 0)
1684 return 1;
1686 else
1688 Lisp_Object contail;
1690 for (contail = conditions; CONSP (contail); contail = XCDR (contail))
1691 if (EQ (XCAR (tail), XCAR (contail)))
1692 return 1;
1696 return 0;
1699 /* Call the debugger if calling it is currently enabled for CONDITIONS.
1700 SIG and DATA describe the signal. There are two ways to pass them:
1701 = SIG is the error symbol, and DATA is the rest of the data.
1702 = SIG is nil, and DATA is (SYMBOL . REST-OF-DATA).
1703 This is for memory-full errors only. */
1704 static bool
1705 maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig, Lisp_Object data)
1707 Lisp_Object combined_data;
1709 combined_data = Fcons (sig, data);
1711 if (
1712 /* Don't try to run the debugger with interrupts blocked.
1713 The editing loop would return anyway. */
1714 ! input_blocked_p ()
1715 && NILP (Vinhibit_debugger)
1716 /* Does user want to enter debugger for this kind of error? */
1717 && (EQ (sig, Qquit)
1718 ? debug_on_quit
1719 : wants_debugger (Vdebug_on_error, conditions))
1720 && ! skip_debugger (conditions, combined_data)
1721 /* RMS: What's this for? */
1722 && when_entered_debugger < num_nonmacro_input_events)
1724 call_debugger (list2 (Qerror, combined_data));
1725 return 1;
1728 return 0;
1731 static Lisp_Object
1732 find_handler_clause (Lisp_Object handlers, Lisp_Object conditions)
1734 register Lisp_Object h;
1736 /* t is used by handlers for all conditions, set up by C code. */
1737 if (EQ (handlers, Qt))
1738 return Qt;
1740 /* error is used similarly, but means print an error message
1741 and run the debugger if that is enabled. */
1742 if (EQ (handlers, Qerror))
1743 return Qt;
1745 for (h = handlers; CONSP (h); h = XCDR (h))
1747 Lisp_Object handler = XCAR (h);
1748 if (!NILP (Fmemq (handler, conditions)))
1749 return handlers;
1752 return Qnil;
1756 /* Dump an error message; called like vprintf. */
1757 void
1758 verror (const char *m, va_list ap)
1760 char buf[4000];
1761 ptrdiff_t size = sizeof buf;
1762 ptrdiff_t size_max = STRING_BYTES_BOUND + 1;
1763 char *buffer = buf;
1764 ptrdiff_t used;
1765 Lisp_Object string;
1767 used = evxprintf (&buffer, &size, buf, size_max, m, ap);
1768 string = make_string (buffer, used);
1769 if (buffer != buf)
1770 xfree (buffer);
1772 xsignal1 (Qerror, string);
1776 /* Dump an error message; called like printf. */
1778 /* VARARGS 1 */
1779 void
1780 error (const char *m, ...)
1782 va_list ap;
1783 va_start (ap, m);
1784 verror (m, ap);
1787 DEFUN ("commandp", Fcommandp, Scommandp, 1, 2, 0,
1788 doc: /* Non-nil if FUNCTION makes provisions for interactive calling.
1789 This means it contains a description for how to read arguments to give it.
1790 The value is nil for an invalid function or a symbol with no function
1791 definition.
1793 Interactively callable functions include strings and vectors (treated
1794 as keyboard macros), lambda-expressions that contain a top-level call
1795 to `interactive', autoload definitions made by `autoload' with non-nil
1796 fourth argument, and some of the built-in functions of Lisp.
1798 Also, a symbol satisfies `commandp' if its function definition does so.
1800 If the optional argument FOR-CALL-INTERACTIVELY is non-nil,
1801 then strings and vectors are not accepted. */)
1802 (Lisp_Object function, Lisp_Object for_call_interactively)
1804 register Lisp_Object fun;
1805 register Lisp_Object funcar;
1806 Lisp_Object if_prop = Qnil;
1808 fun = function;
1810 fun = indirect_function (fun); /* Check cycles. */
1811 if (NILP (fun))
1812 return Qnil;
1814 /* Check an `interactive-form' property if present, analogous to the
1815 function-documentation property. */
1816 fun = function;
1817 while (SYMBOLP (fun))
1819 Lisp_Object tmp = Fget (fun, Qinteractive_form);
1820 if (!NILP (tmp))
1821 if_prop = Qt;
1822 fun = Fsymbol_function (fun);
1825 /* Emacs primitives are interactive if their DEFUN specifies an
1826 interactive spec. */
1827 if (SUBRP (fun))
1828 return XSUBR (fun)->intspec ? Qt : if_prop;
1830 /* Bytecode objects are interactive if they are long enough to
1831 have an element whose index is COMPILED_INTERACTIVE, which is
1832 where the interactive spec is stored. */
1833 else if (COMPILEDP (fun))
1834 return ((ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK) > COMPILED_INTERACTIVE
1835 ? Qt : if_prop);
1837 /* Strings and vectors are keyboard macros. */
1838 if (STRINGP (fun) || VECTORP (fun))
1839 return (NILP (for_call_interactively) ? Qt : Qnil);
1841 /* Lists may represent commands. */
1842 if (!CONSP (fun))
1843 return Qnil;
1844 funcar = XCAR (fun);
1845 if (EQ (funcar, Qclosure))
1846 return (!NILP (Fassq (Qinteractive, Fcdr (Fcdr (XCDR (fun)))))
1847 ? Qt : if_prop);
1848 else if (EQ (funcar, Qlambda))
1849 return !NILP (Fassq (Qinteractive, Fcdr (XCDR (fun)))) ? Qt : if_prop;
1850 else if (EQ (funcar, Qautoload))
1851 return !NILP (Fcar (Fcdr (Fcdr (XCDR (fun))))) ? Qt : if_prop;
1852 else
1853 return Qnil;
1856 DEFUN ("autoload", Fautoload, Sautoload, 2, 5, 0,
1857 doc: /* Define FUNCTION to autoload from FILE.
1858 FUNCTION is a symbol; FILE is a file name string to pass to `load'.
1859 Third arg DOCSTRING is documentation for the function.
1860 Fourth arg INTERACTIVE if non-nil says function can be called interactively.
1861 Fifth arg TYPE indicates the type of the object:
1862 nil or omitted says FUNCTION is a function,
1863 `keymap' says FUNCTION is really a keymap, and
1864 `macro' or t says FUNCTION is really a macro.
1865 Third through fifth args give info about the real definition.
1866 They default to nil.
1867 If FUNCTION is already defined other than as an autoload,
1868 this does nothing and returns nil. */)
1869 (Lisp_Object function, Lisp_Object file, Lisp_Object docstring, Lisp_Object interactive, Lisp_Object type)
1871 CHECK_SYMBOL (function);
1872 CHECK_STRING (file);
1874 /* If function is defined and not as an autoload, don't override. */
1875 if (!NILP (XSYMBOL (function)->function)
1876 && !AUTOLOADP (XSYMBOL (function)->function))
1877 return Qnil;
1879 if (!NILP (Vpurify_flag) && EQ (docstring, make_number (0)))
1880 /* `read1' in lread.c has found the docstring starting with "\
1881 and assumed the docstring will be provided by Snarf-documentation, so it
1882 passed us 0 instead. But that leads to accidental sharing in purecopy's
1883 hash-consing, so we use a (hopefully) unique integer instead. */
1884 docstring = make_number (XHASH (function));
1885 return Fdefalias (function,
1886 list5 (Qautoload, file, docstring, interactive, type),
1887 Qnil);
1890 void
1891 un_autoload (Lisp_Object oldqueue)
1893 Lisp_Object queue, first, second;
1895 /* Queue to unwind is current value of Vautoload_queue.
1896 oldqueue is the shadowed value to leave in Vautoload_queue. */
1897 queue = Vautoload_queue;
1898 Vautoload_queue = oldqueue;
1899 while (CONSP (queue))
1901 first = XCAR (queue);
1902 second = Fcdr (first);
1903 first = Fcar (first);
1904 if (EQ (first, make_number (0)))
1905 Vfeatures = second;
1906 else
1907 Ffset (first, second);
1908 queue = XCDR (queue);
1912 /* Load an autoloaded function.
1913 FUNNAME is the symbol which is the function's name.
1914 FUNDEF is the autoload definition (a list). */
1916 DEFUN ("autoload-do-load", Fautoload_do_load, Sautoload_do_load, 1, 3, 0,
1917 doc: /* Load FUNDEF which should be an autoload.
1918 If non-nil, FUNNAME should be the symbol whose function value is FUNDEF,
1919 in which case the function returns the new autoloaded function value.
1920 If equal to `macro', MACRO-ONLY specifies that FUNDEF should only be loaded if
1921 it is defines a macro. */)
1922 (Lisp_Object fundef, Lisp_Object funname, Lisp_Object macro_only)
1924 ptrdiff_t count = SPECPDL_INDEX ();
1925 struct gcpro gcpro1, gcpro2, gcpro3;
1927 if (!CONSP (fundef) || !EQ (Qautoload, XCAR (fundef)))
1928 return fundef;
1930 if (EQ (macro_only, Qmacro))
1932 Lisp_Object kind = Fnth (make_number (4), fundef);
1933 if (! (EQ (kind, Qt) || EQ (kind, Qmacro)))
1934 return fundef;
1937 /* This is to make sure that loadup.el gives a clear picture
1938 of what files are preloaded and when. */
1939 if (! NILP (Vpurify_flag))
1940 error ("Attempt to autoload %s while preparing to dump",
1941 SDATA (SYMBOL_NAME (funname)));
1943 CHECK_SYMBOL (funname);
1944 GCPRO3 (funname, fundef, macro_only);
1946 /* Preserve the match data. */
1947 record_unwind_save_match_data ();
1949 /* If autoloading gets an error (which includes the error of failing
1950 to define the function being called), we use Vautoload_queue
1951 to undo function definitions and `provide' calls made by
1952 the function. We do this in the specific case of autoloading
1953 because autoloading is not an explicit request "load this file",
1954 but rather a request to "call this function".
1956 The value saved here is to be restored into Vautoload_queue. */
1957 record_unwind_protect (un_autoload, Vautoload_queue);
1958 Vautoload_queue = Qt;
1959 /* If `macro_only', assume this autoload to be a "best-effort",
1960 so don't signal an error if autoloading fails. */
1961 Fload (Fcar (Fcdr (fundef)), macro_only, Qt, Qnil, Qt);
1963 /* Once loading finishes, don't undo it. */
1964 Vautoload_queue = Qt;
1965 unbind_to (count, Qnil);
1967 UNGCPRO;
1969 if (NILP (funname))
1970 return Qnil;
1971 else
1973 Lisp_Object fun = Findirect_function (funname, Qnil);
1975 if (!NILP (Fequal (fun, fundef)))
1976 error ("Autoloading failed to define function %s",
1977 SDATA (SYMBOL_NAME (funname)));
1978 else
1979 return fun;
1984 DEFUN ("eval", Feval, Seval, 1, 2, 0,
1985 doc: /* Evaluate FORM and return its value.
1986 If LEXICAL is t, evaluate using lexical scoping.
1987 LEXICAL can also be an actual lexical environment, in the form of an
1988 alist mapping symbols to their value. */)
1989 (Lisp_Object form, Lisp_Object lexical)
1991 ptrdiff_t count = SPECPDL_INDEX ();
1992 specbind (Qinternal_interpreter_environment,
1993 CONSP (lexical) || NILP (lexical) ? lexical : list1 (Qt));
1994 return unbind_to (count, eval_sub (form));
1997 /* Grow the specpdl stack by one entry.
1998 The caller should have already initialized the entry.
1999 Signal an error on stack overflow.
2001 Make sure that there is always one unused entry past the top of the
2002 stack, so that the just-initialized entry is safely unwound if
2003 memory exhausted and an error is signaled here. Also, allocate a
2004 never-used entry just before the bottom of the stack; sometimes its
2005 address is taken. */
2007 static void
2008 grow_specpdl (void)
2010 specpdl_ptr++;
2012 if (specpdl_ptr == specpdl + specpdl_size)
2014 ptrdiff_t count = SPECPDL_INDEX ();
2015 ptrdiff_t max_size = min (max_specpdl_size, PTRDIFF_MAX - 1000);
2016 union specbinding *pdlvec = specpdl - 1;
2017 ptrdiff_t pdlvecsize = specpdl_size + 1;
2018 if (max_size <= specpdl_size)
2020 if (max_specpdl_size < 400)
2021 max_size = max_specpdl_size = 400;
2022 if (max_size <= specpdl_size)
2023 signal_error ("Variable binding depth exceeds max-specpdl-size",
2024 Qnil);
2026 pdlvec = xpalloc (pdlvec, &pdlvecsize, 1, max_size + 1, sizeof *specpdl);
2027 specpdl = pdlvec + 1;
2028 specpdl_size = pdlvecsize - 1;
2029 specpdl_ptr = specpdl + count;
2033 ptrdiff_t
2034 record_in_backtrace (Lisp_Object function, Lisp_Object *args, ptrdiff_t nargs)
2036 ptrdiff_t count = SPECPDL_INDEX ();
2038 eassert (nargs >= UNEVALLED);
2039 specpdl_ptr->bt.kind = SPECPDL_BACKTRACE;
2040 specpdl_ptr->bt.debug_on_exit = false;
2041 specpdl_ptr->bt.function = function;
2042 specpdl_ptr->bt.args = args;
2043 specpdl_ptr->bt.nargs = nargs;
2044 grow_specpdl ();
2046 return count;
2049 /* Eval a sub-expression of the current expression (i.e. in the same
2050 lexical scope). */
2051 Lisp_Object
2052 eval_sub (Lisp_Object form)
2054 Lisp_Object fun, val, original_fun, original_args;
2055 Lisp_Object funcar;
2056 struct gcpro gcpro1, gcpro2, gcpro3;
2057 ptrdiff_t count;
2059 if (SYMBOLP (form))
2061 /* Look up its binding in the lexical environment.
2062 We do not pay attention to the declared_special flag here, since we
2063 already did that when let-binding the variable. */
2064 Lisp_Object lex_binding
2065 = !NILP (Vinternal_interpreter_environment) /* Mere optimization! */
2066 ? Fassq (form, Vinternal_interpreter_environment)
2067 : Qnil;
2068 if (CONSP (lex_binding))
2069 return XCDR (lex_binding);
2070 else
2071 return Fsymbol_value (form);
2074 if (!CONSP (form))
2075 return form;
2077 QUIT;
2079 GCPRO1 (form);
2080 maybe_gc ();
2081 UNGCPRO;
2083 if (++lisp_eval_depth > max_lisp_eval_depth)
2085 if (max_lisp_eval_depth < 100)
2086 max_lisp_eval_depth = 100;
2087 if (lisp_eval_depth > max_lisp_eval_depth)
2088 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2091 original_fun = XCAR (form);
2092 original_args = XCDR (form);
2094 /* This also protects them from gc. */
2095 count = record_in_backtrace (original_fun, &original_args, UNEVALLED);
2097 if (debug_on_next_call)
2098 do_debug_on_call (Qt, count);
2100 /* At this point, only original_fun and original_args
2101 have values that will be used below. */
2102 retry:
2104 /* Optimize for no indirection. */
2105 fun = original_fun;
2106 if (!SYMBOLP (fun))
2107 fun = Ffunction (Fcons (fun, Qnil));
2108 else if (!NILP (fun) && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2109 fun = indirect_function (fun);
2111 if (SUBRP (fun))
2113 Lisp_Object numargs;
2114 Lisp_Object argvals[8];
2115 Lisp_Object args_left;
2116 register int i, maxargs;
2118 args_left = original_args;
2119 numargs = Flength (args_left);
2121 check_cons_list ();
2123 if (XINT (numargs) < XSUBR (fun)->min_args
2124 || (XSUBR (fun)->max_args >= 0
2125 && XSUBR (fun)->max_args < XINT (numargs)))
2126 xsignal2 (Qwrong_number_of_arguments, original_fun, numargs);
2128 else if (XSUBR (fun)->max_args == UNEVALLED)
2129 val = (XSUBR (fun)->function.aUNEVALLED) (args_left);
2130 else if (XSUBR (fun)->max_args == MANY)
2132 /* Pass a vector of evaluated arguments. */
2133 Lisp_Object *vals;
2134 ptrdiff_t argnum = 0;
2135 USE_SAFE_ALLOCA;
2137 SAFE_ALLOCA_LISP (vals, XINT (numargs));
2139 GCPRO3 (args_left, fun, fun);
2140 gcpro3.var = vals;
2141 gcpro3.nvars = 0;
2143 while (!NILP (args_left))
2145 vals[argnum++] = eval_sub (Fcar (args_left));
2146 args_left = Fcdr (args_left);
2147 gcpro3.nvars = argnum;
2150 set_backtrace_args (specpdl + count, vals, XINT (numargs));
2152 val = (XSUBR (fun)->function.aMANY) (XINT (numargs), vals);
2153 UNGCPRO;
2154 SAFE_FREE ();
2156 else
2158 GCPRO3 (args_left, fun, fun);
2159 gcpro3.var = argvals;
2160 gcpro3.nvars = 0;
2162 maxargs = XSUBR (fun)->max_args;
2163 for (i = 0; i < maxargs; args_left = Fcdr (args_left))
2165 argvals[i] = eval_sub (Fcar (args_left));
2166 gcpro3.nvars = ++i;
2169 UNGCPRO;
2171 set_backtrace_args (specpdl + count, argvals, XINT (numargs));
2173 switch (i)
2175 case 0:
2176 val = (XSUBR (fun)->function.a0 ());
2177 break;
2178 case 1:
2179 val = (XSUBR (fun)->function.a1 (argvals[0]));
2180 break;
2181 case 2:
2182 val = (XSUBR (fun)->function.a2 (argvals[0], argvals[1]));
2183 break;
2184 case 3:
2185 val = (XSUBR (fun)->function.a3
2186 (argvals[0], argvals[1], argvals[2]));
2187 break;
2188 case 4:
2189 val = (XSUBR (fun)->function.a4
2190 (argvals[0], argvals[1], argvals[2], argvals[3]));
2191 break;
2192 case 5:
2193 val = (XSUBR (fun)->function.a5
2194 (argvals[0], argvals[1], argvals[2], argvals[3],
2195 argvals[4]));
2196 break;
2197 case 6:
2198 val = (XSUBR (fun)->function.a6
2199 (argvals[0], argvals[1], argvals[2], argvals[3],
2200 argvals[4], argvals[5]));
2201 break;
2202 case 7:
2203 val = (XSUBR (fun)->function.a7
2204 (argvals[0], argvals[1], argvals[2], argvals[3],
2205 argvals[4], argvals[5], argvals[6]));
2206 break;
2208 case 8:
2209 val = (XSUBR (fun)->function.a8
2210 (argvals[0], argvals[1], argvals[2], argvals[3],
2211 argvals[4], argvals[5], argvals[6], argvals[7]));
2212 break;
2214 default:
2215 /* Someone has created a subr that takes more arguments than
2216 is supported by this code. We need to either rewrite the
2217 subr to use a different argument protocol, or add more
2218 cases to this switch. */
2219 emacs_abort ();
2223 else if (COMPILEDP (fun))
2224 val = apply_lambda (fun, original_args, count);
2225 else
2227 if (NILP (fun))
2228 xsignal1 (Qvoid_function, original_fun);
2229 if (!CONSP (fun))
2230 xsignal1 (Qinvalid_function, original_fun);
2231 funcar = XCAR (fun);
2232 if (!SYMBOLP (funcar))
2233 xsignal1 (Qinvalid_function, original_fun);
2234 if (EQ (funcar, Qautoload))
2236 Fautoload_do_load (fun, original_fun, Qnil);
2237 goto retry;
2239 if (EQ (funcar, Qmacro))
2241 ptrdiff_t count1 = SPECPDL_INDEX ();
2242 Lisp_Object exp;
2243 /* Bind lexical-binding during expansion of the macro, so the
2244 macro can know reliably if the code it outputs will be
2245 interpreted using lexical-binding or not. */
2246 specbind (Qlexical_binding,
2247 NILP (Vinternal_interpreter_environment) ? Qnil : Qt);
2248 exp = apply1 (Fcdr (fun), original_args);
2249 unbind_to (count1, Qnil);
2250 val = eval_sub (exp);
2252 else if (EQ (funcar, Qlambda)
2253 || EQ (funcar, Qclosure))
2254 val = apply_lambda (fun, original_args, count);
2255 else
2256 xsignal1 (Qinvalid_function, original_fun);
2258 check_cons_list ();
2260 lisp_eval_depth--;
2261 if (backtrace_debug_on_exit (specpdl + count))
2262 val = call_debugger (list2 (Qexit, val));
2263 specpdl_ptr--;
2265 return val;
2268 DEFUN ("apply", Fapply, Sapply, 1, MANY, 0,
2269 doc: /* Call FUNCTION with our remaining args, using our last arg as list of args.
2270 Then return the value FUNCTION returns.
2271 Thus, (apply '+ 1 2 '(3 4)) returns 10.
2272 usage: (apply FUNCTION &rest ARGUMENTS) */)
2273 (ptrdiff_t nargs, Lisp_Object *args)
2275 ptrdiff_t i, numargs, funcall_nargs;
2276 register Lisp_Object *funcall_args = NULL;
2277 register Lisp_Object spread_arg = args[nargs - 1];
2278 Lisp_Object fun = args[0];
2279 Lisp_Object retval;
2280 USE_SAFE_ALLOCA;
2282 CHECK_LIST (spread_arg);
2284 numargs = XINT (Flength (spread_arg));
2286 if (numargs == 0)
2287 return Ffuncall (nargs - 1, args);
2288 else if (numargs == 1)
2290 args [nargs - 1] = XCAR (spread_arg);
2291 return Ffuncall (nargs, args);
2294 numargs += nargs - 2;
2296 /* Optimize for no indirection. */
2297 if (SYMBOLP (fun) && !NILP (fun)
2298 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2300 fun = indirect_function (fun);
2301 if (NILP (fun))
2302 /* Let funcall get the error. */
2303 fun = args[0];
2306 if (SUBRP (fun) && XSUBR (fun)->max_args > numargs
2307 /* Don't hide an error by adding missing arguments. */
2308 && numargs >= XSUBR (fun)->min_args)
2310 /* Avoid making funcall cons up a yet another new vector of arguments
2311 by explicitly supplying nil's for optional values. */
2312 SAFE_ALLOCA_LISP (funcall_args, 1 + XSUBR (fun)->max_args);
2313 for (i = numargs; i < XSUBR (fun)->max_args; /* nothing */)
2314 funcall_args[++i] = Qnil;
2315 funcall_nargs = 1 + XSUBR (fun)->max_args;
2317 else
2318 { /* We add 1 to numargs because funcall_args includes the
2319 function itself as well as its arguments. */
2320 SAFE_ALLOCA_LISP (funcall_args, 1 + numargs);
2321 funcall_nargs = 1 + numargs;
2324 memcpy (funcall_args, args, nargs * word_size);
2325 /* Spread the last arg we got. Its first element goes in
2326 the slot that it used to occupy, hence this value of I. */
2327 i = nargs - 1;
2328 while (!NILP (spread_arg))
2330 funcall_args [i++] = XCAR (spread_arg);
2331 spread_arg = XCDR (spread_arg);
2334 /* Ffuncall gcpro's all of its args. */
2335 retval = Ffuncall (funcall_nargs, funcall_args);
2337 SAFE_FREE ();
2338 return retval;
2341 /* Run hook variables in various ways. */
2343 static Lisp_Object
2344 funcall_nil (ptrdiff_t nargs, Lisp_Object *args)
2346 Ffuncall (nargs, args);
2347 return Qnil;
2350 DEFUN ("run-hooks", Frun_hooks, Srun_hooks, 0, MANY, 0,
2351 doc: /* Run each hook in HOOKS.
2352 Each argument should be a symbol, a hook variable.
2353 These symbols are processed in the order specified.
2354 If a hook symbol has a non-nil value, that value may be a function
2355 or a list of functions to be called to run the hook.
2356 If the value is a function, it is called with no arguments.
2357 If it is a list, the elements are called, in order, with no arguments.
2359 Major modes should not use this function directly to run their mode
2360 hook; they should use `run-mode-hooks' instead.
2362 Do not use `make-local-variable' to make a hook variable buffer-local.
2363 Instead, use `add-hook' and specify t for the LOCAL argument.
2364 usage: (run-hooks &rest HOOKS) */)
2365 (ptrdiff_t nargs, Lisp_Object *args)
2367 Lisp_Object hook[1];
2368 ptrdiff_t i;
2370 for (i = 0; i < nargs; i++)
2372 hook[0] = args[i];
2373 run_hook_with_args (1, hook, funcall_nil);
2376 return Qnil;
2379 DEFUN ("run-hook-with-args", Frun_hook_with_args,
2380 Srun_hook_with_args, 1, MANY, 0,
2381 doc: /* Run HOOK with the specified arguments ARGS.
2382 HOOK should be a symbol, a hook variable. The value of HOOK
2383 may be nil, a function, or a list of functions. Call each
2384 function in order with arguments ARGS. The final return value
2385 is unspecified.
2387 Do not use `make-local-variable' to make a hook variable buffer-local.
2388 Instead, use `add-hook' and specify t for the LOCAL argument.
2389 usage: (run-hook-with-args HOOK &rest ARGS) */)
2390 (ptrdiff_t nargs, Lisp_Object *args)
2392 return run_hook_with_args (nargs, args, funcall_nil);
2395 /* NB this one still documents a specific non-nil return value.
2396 (As did run-hook-with-args and run-hook-with-args-until-failure
2397 until they were changed in 24.1.) */
2398 DEFUN ("run-hook-with-args-until-success", Frun_hook_with_args_until_success,
2399 Srun_hook_with_args_until_success, 1, MANY, 0,
2400 doc: /* Run HOOK with the specified arguments ARGS.
2401 HOOK should be a symbol, a hook variable. The value of HOOK
2402 may be nil, a function, or a list of functions. Call each
2403 function in order with arguments ARGS, stopping at the first
2404 one that returns non-nil, and return that value. Otherwise (if
2405 all functions return nil, or if there are no functions to call),
2406 return nil.
2408 Do not use `make-local-variable' to make a hook variable buffer-local.
2409 Instead, use `add-hook' and specify t for the LOCAL argument.
2410 usage: (run-hook-with-args-until-success HOOK &rest ARGS) */)
2411 (ptrdiff_t nargs, Lisp_Object *args)
2413 return run_hook_with_args (nargs, args, Ffuncall);
2416 static Lisp_Object
2417 funcall_not (ptrdiff_t nargs, Lisp_Object *args)
2419 return NILP (Ffuncall (nargs, args)) ? Qt : Qnil;
2422 DEFUN ("run-hook-with-args-until-failure", Frun_hook_with_args_until_failure,
2423 Srun_hook_with_args_until_failure, 1, MANY, 0,
2424 doc: /* Run HOOK with the specified arguments ARGS.
2425 HOOK should be a symbol, a hook variable. The value of HOOK
2426 may be nil, a function, or a list of functions. Call each
2427 function in order with arguments ARGS, stopping at the first
2428 one that returns nil, and return nil. Otherwise (if all functions
2429 return non-nil, or if there are no functions to call), return non-nil
2430 \(do not rely on the precise return value in this case).
2432 Do not use `make-local-variable' to make a hook variable buffer-local.
2433 Instead, use `add-hook' and specify t for the LOCAL argument.
2434 usage: (run-hook-with-args-until-failure HOOK &rest ARGS) */)
2435 (ptrdiff_t nargs, Lisp_Object *args)
2437 return NILP (run_hook_with_args (nargs, args, funcall_not)) ? Qt : Qnil;
2440 static Lisp_Object
2441 run_hook_wrapped_funcall (ptrdiff_t nargs, Lisp_Object *args)
2443 Lisp_Object tmp = args[0], ret;
2444 args[0] = args[1];
2445 args[1] = tmp;
2446 ret = Ffuncall (nargs, args);
2447 args[1] = args[0];
2448 args[0] = tmp;
2449 return ret;
2452 DEFUN ("run-hook-wrapped", Frun_hook_wrapped, Srun_hook_wrapped, 2, MANY, 0,
2453 doc: /* Run HOOK, passing each function through WRAP-FUNCTION.
2454 I.e. instead of calling each function FUN directly with arguments ARGS,
2455 it calls WRAP-FUNCTION with arguments FUN and ARGS.
2456 As soon as a call to WRAP-FUNCTION returns non-nil, `run-hook-wrapped'
2457 aborts and returns that value.
2458 usage: (run-hook-wrapped HOOK WRAP-FUNCTION &rest ARGS) */)
2459 (ptrdiff_t nargs, Lisp_Object *args)
2461 return run_hook_with_args (nargs, args, run_hook_wrapped_funcall);
2464 /* ARGS[0] should be a hook symbol.
2465 Call each of the functions in the hook value, passing each of them
2466 as arguments all the rest of ARGS (all NARGS - 1 elements).
2467 FUNCALL specifies how to call each function on the hook.
2468 The caller (or its caller, etc) must gcpro all of ARGS,
2469 except that it isn't necessary to gcpro ARGS[0]. */
2471 Lisp_Object
2472 run_hook_with_args (ptrdiff_t nargs, Lisp_Object *args,
2473 Lisp_Object (*funcall) (ptrdiff_t nargs, Lisp_Object *args))
2475 Lisp_Object sym, val, ret = Qnil;
2476 struct gcpro gcpro1, gcpro2, gcpro3;
2478 /* If we are dying or still initializing,
2479 don't do anything--it would probably crash if we tried. */
2480 if (NILP (Vrun_hooks))
2481 return Qnil;
2483 sym = args[0];
2484 val = find_symbol_value (sym);
2486 if (EQ (val, Qunbound) || NILP (val))
2487 return ret;
2488 else if (!CONSP (val) || FUNCTIONP (val))
2490 args[0] = val;
2491 return funcall (nargs, args);
2493 else
2495 Lisp_Object global_vals = Qnil;
2496 GCPRO3 (sym, val, global_vals);
2498 for (;
2499 CONSP (val) && NILP (ret);
2500 val = XCDR (val))
2502 if (EQ (XCAR (val), Qt))
2504 /* t indicates this hook has a local binding;
2505 it means to run the global binding too. */
2506 global_vals = Fdefault_value (sym);
2507 if (NILP (global_vals)) continue;
2509 if (!CONSP (global_vals) || EQ (XCAR (global_vals), Qlambda))
2511 args[0] = global_vals;
2512 ret = funcall (nargs, args);
2514 else
2516 for (;
2517 CONSP (global_vals) && NILP (ret);
2518 global_vals = XCDR (global_vals))
2520 args[0] = XCAR (global_vals);
2521 /* In a global value, t should not occur. If it does, we
2522 must ignore it to avoid an endless loop. */
2523 if (!EQ (args[0], Qt))
2524 ret = funcall (nargs, args);
2528 else
2530 args[0] = XCAR (val);
2531 ret = funcall (nargs, args);
2535 UNGCPRO;
2536 return ret;
2540 /* Run the hook HOOK, giving each function the two args ARG1 and ARG2. */
2542 void
2543 run_hook_with_args_2 (Lisp_Object hook, Lisp_Object arg1, Lisp_Object arg2)
2545 Frun_hook_with_args (3, ((Lisp_Object []) { hook, arg1, arg2 }));
2548 /* Apply fn to arg. */
2549 Lisp_Object
2550 apply1 (Lisp_Object fn, Lisp_Object arg)
2552 return (NILP (arg) ? Ffuncall (1, &fn)
2553 : Fapply (2, ((Lisp_Object []) { fn, arg })));
2556 /* Call function fn on no arguments. */
2557 Lisp_Object
2558 call0 (Lisp_Object fn)
2560 return Ffuncall (1, &fn);
2563 /* Call function fn with 1 argument arg1. */
2564 /* ARGSUSED */
2565 Lisp_Object
2566 call1 (Lisp_Object fn, Lisp_Object arg1)
2568 return Ffuncall (2, ((Lisp_Object []) { fn, arg1 }));
2571 /* Call function fn with 2 arguments arg1, arg2. */
2572 /* ARGSUSED */
2573 Lisp_Object
2574 call2 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2)
2576 return Ffuncall (3, ((Lisp_Object []) { fn, arg1, arg2 }));
2579 /* Call function fn with 3 arguments arg1, arg2, arg3. */
2580 /* ARGSUSED */
2581 Lisp_Object
2582 call3 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2584 return Ffuncall (4, ((Lisp_Object []) { fn, arg1, arg2, arg3 }));
2587 /* Call function fn with 4 arguments arg1, arg2, arg3, arg4. */
2588 /* ARGSUSED */
2589 Lisp_Object
2590 call4 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2591 Lisp_Object arg4)
2593 return Ffuncall (5, ((Lisp_Object []) { fn, arg1, arg2, arg3, arg4 }));
2596 /* Call function fn with 5 arguments arg1, arg2, arg3, arg4, arg5. */
2597 /* ARGSUSED */
2598 Lisp_Object
2599 call5 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2600 Lisp_Object arg4, Lisp_Object arg5)
2602 return Ffuncall (6, ((Lisp_Object []) { fn, arg1, arg2, arg3, arg4, arg5 }));
2605 /* Call function fn with 6 arguments arg1, arg2, arg3, arg4, arg5, arg6. */
2606 /* ARGSUSED */
2607 Lisp_Object
2608 call6 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2609 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6)
2611 return Ffuncall (7, ((Lisp_Object [])
2612 { fn, arg1, arg2, arg3, arg4, arg5, arg6 }));
2615 /* Call function fn with 7 arguments arg1, arg2, arg3, arg4, arg5, arg6, arg7. */
2616 /* ARGSUSED */
2617 Lisp_Object
2618 call7 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2619 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6, Lisp_Object arg7)
2621 return Ffuncall (8, ((Lisp_Object [])
2622 { fn, arg1, arg2, arg3, arg4, arg5, arg6, arg7 }));
2625 /* The caller should GCPRO all the elements of ARGS. */
2627 DEFUN ("functionp", Ffunctionp, Sfunctionp, 1, 1, 0,
2628 doc: /* Non-nil if OBJECT is a function. */)
2629 (Lisp_Object object)
2631 if (FUNCTIONP (object))
2632 return Qt;
2633 return Qnil;
2636 DEFUN ("funcall", Ffuncall, Sfuncall, 1, MANY, 0,
2637 doc: /* Call first argument as a function, passing remaining arguments to it.
2638 Return the value that function returns.
2639 Thus, (funcall 'cons 'x 'y) returns (x . y).
2640 usage: (funcall FUNCTION &rest ARGUMENTS) */)
2641 (ptrdiff_t nargs, Lisp_Object *args)
2643 Lisp_Object fun, original_fun;
2644 Lisp_Object funcar;
2645 ptrdiff_t numargs = nargs - 1;
2646 Lisp_Object lisp_numargs;
2647 Lisp_Object val;
2648 register Lisp_Object *internal_args;
2649 ptrdiff_t i, count;
2651 QUIT;
2653 if (++lisp_eval_depth > max_lisp_eval_depth)
2655 if (max_lisp_eval_depth < 100)
2656 max_lisp_eval_depth = 100;
2657 if (lisp_eval_depth > max_lisp_eval_depth)
2658 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2661 /* This also GCPROs them. */
2662 count = record_in_backtrace (args[0], &args[1], nargs - 1);
2664 /* Call GC after setting up the backtrace, so the latter GCPROs the args. */
2665 maybe_gc ();
2667 if (debug_on_next_call)
2668 do_debug_on_call (Qlambda, count);
2670 check_cons_list ();
2672 original_fun = args[0];
2674 retry:
2676 /* Optimize for no indirection. */
2677 fun = original_fun;
2678 if (SYMBOLP (fun) && !NILP (fun)
2679 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2680 fun = indirect_function (fun);
2682 if (SUBRP (fun))
2684 if (numargs < XSUBR (fun)->min_args
2685 || (XSUBR (fun)->max_args >= 0 && XSUBR (fun)->max_args < numargs))
2687 XSETFASTINT (lisp_numargs, numargs);
2688 xsignal2 (Qwrong_number_of_arguments, original_fun, lisp_numargs);
2691 else if (XSUBR (fun)->max_args == UNEVALLED)
2692 xsignal1 (Qinvalid_function, original_fun);
2694 else if (XSUBR (fun)->max_args == MANY)
2695 val = (XSUBR (fun)->function.aMANY) (numargs, args + 1);
2696 else
2698 Lisp_Object internal_argbuf[8];
2699 if (XSUBR (fun)->max_args > numargs)
2701 eassert (XSUBR (fun)->max_args <= ARRAYELTS (internal_argbuf));
2702 internal_args = internal_argbuf;
2703 memcpy (internal_args, args + 1, numargs * word_size);
2704 for (i = numargs; i < XSUBR (fun)->max_args; i++)
2705 internal_args[i] = Qnil;
2707 else
2708 internal_args = args + 1;
2709 switch (XSUBR (fun)->max_args)
2711 case 0:
2712 val = (XSUBR (fun)->function.a0 ());
2713 break;
2714 case 1:
2715 val = (XSUBR (fun)->function.a1 (internal_args[0]));
2716 break;
2717 case 2:
2718 val = (XSUBR (fun)->function.a2
2719 (internal_args[0], internal_args[1]));
2720 break;
2721 case 3:
2722 val = (XSUBR (fun)->function.a3
2723 (internal_args[0], internal_args[1], internal_args[2]));
2724 break;
2725 case 4:
2726 val = (XSUBR (fun)->function.a4
2727 (internal_args[0], internal_args[1], internal_args[2],
2728 internal_args[3]));
2729 break;
2730 case 5:
2731 val = (XSUBR (fun)->function.a5
2732 (internal_args[0], internal_args[1], internal_args[2],
2733 internal_args[3], internal_args[4]));
2734 break;
2735 case 6:
2736 val = (XSUBR (fun)->function.a6
2737 (internal_args[0], internal_args[1], internal_args[2],
2738 internal_args[3], internal_args[4], internal_args[5]));
2739 break;
2740 case 7:
2741 val = (XSUBR (fun)->function.a7
2742 (internal_args[0], internal_args[1], internal_args[2],
2743 internal_args[3], internal_args[4], internal_args[5],
2744 internal_args[6]));
2745 break;
2747 case 8:
2748 val = (XSUBR (fun)->function.a8
2749 (internal_args[0], internal_args[1], internal_args[2],
2750 internal_args[3], internal_args[4], internal_args[5],
2751 internal_args[6], internal_args[7]));
2752 break;
2754 default:
2756 /* If a subr takes more than 8 arguments without using MANY
2757 or UNEVALLED, we need to extend this function to support it.
2758 Until this is done, there is no way to call the function. */
2759 emacs_abort ();
2763 else if (COMPILEDP (fun))
2764 val = funcall_lambda (fun, numargs, args + 1);
2765 else
2767 if (NILP (fun))
2768 xsignal1 (Qvoid_function, original_fun);
2769 if (!CONSP (fun))
2770 xsignal1 (Qinvalid_function, original_fun);
2771 funcar = XCAR (fun);
2772 if (!SYMBOLP (funcar))
2773 xsignal1 (Qinvalid_function, original_fun);
2774 if (EQ (funcar, Qlambda)
2775 || EQ (funcar, Qclosure))
2776 val = funcall_lambda (fun, numargs, args + 1);
2777 else if (EQ (funcar, Qautoload))
2779 Fautoload_do_load (fun, original_fun, Qnil);
2780 check_cons_list ();
2781 goto retry;
2783 else
2784 xsignal1 (Qinvalid_function, original_fun);
2786 check_cons_list ();
2787 lisp_eval_depth--;
2788 if (backtrace_debug_on_exit (specpdl + count))
2789 val = call_debugger (list2 (Qexit, val));
2790 specpdl_ptr--;
2791 return val;
2794 static Lisp_Object
2795 apply_lambda (Lisp_Object fun, Lisp_Object args, ptrdiff_t count)
2797 Lisp_Object args_left;
2798 ptrdiff_t i;
2799 EMACS_INT numargs;
2800 register Lisp_Object *arg_vector;
2801 struct gcpro gcpro1, gcpro2, gcpro3;
2802 register Lisp_Object tem;
2803 USE_SAFE_ALLOCA;
2805 numargs = XFASTINT (Flength (args));
2806 SAFE_ALLOCA_LISP (arg_vector, numargs);
2807 args_left = args;
2809 GCPRO3 (*arg_vector, args_left, fun);
2810 gcpro1.nvars = 0;
2812 for (i = 0; i < numargs; )
2814 tem = Fcar (args_left), args_left = Fcdr (args_left);
2815 tem = eval_sub (tem);
2816 arg_vector[i++] = tem;
2817 gcpro1.nvars = i;
2820 UNGCPRO;
2822 set_backtrace_args (specpdl + count, arg_vector, i);
2823 tem = funcall_lambda (fun, numargs, arg_vector);
2825 /* Do the debug-on-exit now, while arg_vector still exists. */
2826 if (backtrace_debug_on_exit (specpdl + count))
2828 /* Don't do it again when we return to eval. */
2829 set_backtrace_debug_on_exit (specpdl + count, false);
2830 tem = call_debugger (list2 (Qexit, tem));
2832 SAFE_FREE ();
2833 return tem;
2836 /* Apply a Lisp function FUN to the NARGS evaluated arguments in ARG_VECTOR
2837 and return the result of evaluation.
2838 FUN must be either a lambda-expression or a compiled-code object. */
2840 static Lisp_Object
2841 funcall_lambda (Lisp_Object fun, ptrdiff_t nargs,
2842 register Lisp_Object *arg_vector)
2844 Lisp_Object val, syms_left, next, lexenv;
2845 ptrdiff_t count = SPECPDL_INDEX ();
2846 ptrdiff_t i;
2847 bool optional, rest;
2849 if (CONSP (fun))
2851 if (EQ (XCAR (fun), Qclosure))
2853 fun = XCDR (fun); /* Drop `closure'. */
2854 lexenv = XCAR (fun);
2855 CHECK_LIST_CONS (fun, fun);
2857 else
2858 lexenv = Qnil;
2859 syms_left = XCDR (fun);
2860 if (CONSP (syms_left))
2861 syms_left = XCAR (syms_left);
2862 else
2863 xsignal1 (Qinvalid_function, fun);
2865 else if (COMPILEDP (fun))
2867 syms_left = AREF (fun, COMPILED_ARGLIST);
2868 if (INTEGERP (syms_left))
2869 /* A byte-code object with a non-nil `push args' slot means we
2870 shouldn't bind any arguments, instead just call the byte-code
2871 interpreter directly; it will push arguments as necessary.
2873 Byte-code objects with either a non-existent, or a nil value for
2874 the `push args' slot (the default), have dynamically-bound
2875 arguments, and use the argument-binding code below instead (as do
2876 all interpreted functions, even lexically bound ones). */
2878 /* If we have not actually read the bytecode string
2879 and constants vector yet, fetch them from the file. */
2880 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2881 Ffetch_bytecode (fun);
2882 return exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2883 AREF (fun, COMPILED_CONSTANTS),
2884 AREF (fun, COMPILED_STACK_DEPTH),
2885 syms_left,
2886 nargs, arg_vector);
2888 lexenv = Qnil;
2890 else
2891 emacs_abort ();
2893 i = optional = rest = 0;
2894 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
2896 QUIT;
2898 next = XCAR (syms_left);
2899 if (!SYMBOLP (next))
2900 xsignal1 (Qinvalid_function, fun);
2902 if (EQ (next, Qand_rest))
2903 rest = 1;
2904 else if (EQ (next, Qand_optional))
2905 optional = 1;
2906 else
2908 Lisp_Object arg;
2909 if (rest)
2911 arg = Flist (nargs - i, &arg_vector[i]);
2912 i = nargs;
2914 else if (i < nargs)
2915 arg = arg_vector[i++];
2916 else if (!optional)
2917 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2918 else
2919 arg = Qnil;
2921 /* Bind the argument. */
2922 if (!NILP (lexenv) && SYMBOLP (next))
2923 /* Lexically bind NEXT by adding it to the lexenv alist. */
2924 lexenv = Fcons (Fcons (next, arg), lexenv);
2925 else
2926 /* Dynamically bind NEXT. */
2927 specbind (next, arg);
2931 if (!NILP (syms_left))
2932 xsignal1 (Qinvalid_function, fun);
2933 else if (i < nargs)
2934 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2936 if (!EQ (lexenv, Vinternal_interpreter_environment))
2937 /* Instantiate a new lexical environment. */
2938 specbind (Qinternal_interpreter_environment, lexenv);
2940 if (CONSP (fun))
2941 val = Fprogn (XCDR (XCDR (fun)));
2942 else
2944 /* If we have not actually read the bytecode string
2945 and constants vector yet, fetch them from the file. */
2946 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2947 Ffetch_bytecode (fun);
2948 val = exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2949 AREF (fun, COMPILED_CONSTANTS),
2950 AREF (fun, COMPILED_STACK_DEPTH),
2951 Qnil, 0, 0);
2954 return unbind_to (count, val);
2957 DEFUN ("fetch-bytecode", Ffetch_bytecode, Sfetch_bytecode,
2958 1, 1, 0,
2959 doc: /* If byte-compiled OBJECT is lazy-loaded, fetch it now. */)
2960 (Lisp_Object object)
2962 Lisp_Object tem;
2964 if (COMPILEDP (object) && CONSP (AREF (object, COMPILED_BYTECODE)))
2966 tem = read_doc_string (AREF (object, COMPILED_BYTECODE));
2967 if (!CONSP (tem))
2969 tem = AREF (object, COMPILED_BYTECODE);
2970 if (CONSP (tem) && STRINGP (XCAR (tem)))
2971 error ("Invalid byte code in %s", SDATA (XCAR (tem)));
2972 else
2973 error ("Invalid byte code");
2975 ASET (object, COMPILED_BYTECODE, XCAR (tem));
2976 ASET (object, COMPILED_CONSTANTS, XCDR (tem));
2978 return object;
2981 /* Return true if SYMBOL currently has a let-binding
2982 which was made in the buffer that is now current. */
2984 bool
2985 let_shadows_buffer_binding_p (struct Lisp_Symbol *symbol)
2987 union specbinding *p;
2988 Lisp_Object buf = Fcurrent_buffer ();
2990 for (p = specpdl_ptr; p > specpdl; )
2991 if ((--p)->kind > SPECPDL_LET)
2993 struct Lisp_Symbol *let_bound_symbol = XSYMBOL (specpdl_symbol (p));
2994 eassert (let_bound_symbol->redirect != SYMBOL_VARALIAS);
2995 if (symbol == let_bound_symbol
2996 && EQ (specpdl_where (p), buf))
2997 return 1;
3000 return 0;
3003 bool
3004 let_shadows_global_binding_p (Lisp_Object symbol)
3006 union specbinding *p;
3008 for (p = specpdl_ptr; p > specpdl; )
3009 if ((--p)->kind >= SPECPDL_LET && EQ (specpdl_symbol (p), symbol))
3010 return 1;
3012 return 0;
3015 /* `specpdl_ptr' describes which variable is
3016 let-bound, so it can be properly undone when we unbind_to.
3017 It can be either a plain SPECPDL_LET or a SPECPDL_LET_LOCAL/DEFAULT.
3018 - SYMBOL is the variable being bound. Note that it should not be
3019 aliased (i.e. when let-binding V1 that's aliased to V2, we want
3020 to record V2 here).
3021 - WHERE tells us in which buffer the binding took place.
3022 This is used for SPECPDL_LET_LOCAL bindings (i.e. bindings to a
3023 buffer-local variable) as well as for SPECPDL_LET_DEFAULT bindings,
3024 i.e. bindings to the default value of a variable which can be
3025 buffer-local. */
3027 void
3028 specbind (Lisp_Object symbol, Lisp_Object value)
3030 struct Lisp_Symbol *sym;
3032 CHECK_SYMBOL (symbol);
3033 sym = XSYMBOL (symbol);
3035 start:
3036 switch (sym->redirect)
3038 case SYMBOL_VARALIAS:
3039 sym = indirect_variable (sym); XSETSYMBOL (symbol, sym); goto start;
3040 case SYMBOL_PLAINVAL:
3041 /* The most common case is that of a non-constant symbol with a
3042 trivial value. Make that as fast as we can. */
3043 specpdl_ptr->let.kind = SPECPDL_LET;
3044 specpdl_ptr->let.symbol = symbol;
3045 specpdl_ptr->let.old_value = SYMBOL_VAL (sym);
3046 grow_specpdl ();
3047 if (!sym->constant)
3048 SET_SYMBOL_VAL (sym, value);
3049 else
3050 set_internal (symbol, value, Qnil, 1);
3051 break;
3052 case SYMBOL_LOCALIZED:
3053 if (SYMBOL_BLV (sym)->frame_local)
3054 error ("Frame-local vars cannot be let-bound");
3055 case SYMBOL_FORWARDED:
3057 Lisp_Object ovalue = find_symbol_value (symbol);
3058 specpdl_ptr->let.kind = SPECPDL_LET_LOCAL;
3059 specpdl_ptr->let.symbol = symbol;
3060 specpdl_ptr->let.old_value = ovalue;
3061 specpdl_ptr->let.where = Fcurrent_buffer ();
3063 eassert (sym->redirect != SYMBOL_LOCALIZED
3064 || (EQ (SYMBOL_BLV (sym)->where, Fcurrent_buffer ())));
3066 if (sym->redirect == SYMBOL_LOCALIZED)
3068 if (!blv_found (SYMBOL_BLV (sym)))
3069 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3071 else if (BUFFER_OBJFWDP (SYMBOL_FWD (sym)))
3073 /* If SYMBOL is a per-buffer variable which doesn't have a
3074 buffer-local value here, make the `let' change the global
3075 value by changing the value of SYMBOL in all buffers not
3076 having their own value. This is consistent with what
3077 happens with other buffer-local variables. */
3078 if (NILP (Flocal_variable_p (symbol, Qnil)))
3080 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3081 grow_specpdl ();
3082 Fset_default (symbol, value);
3083 return;
3086 else
3087 specpdl_ptr->let.kind = SPECPDL_LET;
3089 grow_specpdl ();
3090 set_internal (symbol, value, Qnil, 1);
3091 break;
3093 default: emacs_abort ();
3097 /* Push unwind-protect entries of various types. */
3099 void
3100 record_unwind_protect (void (*function) (Lisp_Object), Lisp_Object arg)
3102 specpdl_ptr->unwind.kind = SPECPDL_UNWIND;
3103 specpdl_ptr->unwind.func = function;
3104 specpdl_ptr->unwind.arg = arg;
3105 grow_specpdl ();
3108 void
3109 record_unwind_protect_ptr (void (*function) (void *), void *arg)
3111 specpdl_ptr->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3112 specpdl_ptr->unwind_ptr.func = function;
3113 specpdl_ptr->unwind_ptr.arg = arg;
3114 grow_specpdl ();
3117 void
3118 record_unwind_protect_int (void (*function) (int), int arg)
3120 specpdl_ptr->unwind_int.kind = SPECPDL_UNWIND_INT;
3121 specpdl_ptr->unwind_int.func = function;
3122 specpdl_ptr->unwind_int.arg = arg;
3123 grow_specpdl ();
3126 void
3127 record_unwind_protect_void (void (*function) (void))
3129 specpdl_ptr->unwind_void.kind = SPECPDL_UNWIND_VOID;
3130 specpdl_ptr->unwind_void.func = function;
3131 grow_specpdl ();
3134 static void
3135 do_nothing (void)
3138 /* Push an unwind-protect entry that does nothing, so that
3139 set_unwind_protect_ptr can overwrite it later. */
3141 void
3142 record_unwind_protect_nothing (void)
3144 record_unwind_protect_void (do_nothing);
3147 /* Clear the unwind-protect entry COUNT, so that it does nothing.
3148 It need not be at the top of the stack. */
3150 void
3151 clear_unwind_protect (ptrdiff_t count)
3153 union specbinding *p = specpdl + count;
3154 p->unwind_void.kind = SPECPDL_UNWIND_VOID;
3155 p->unwind_void.func = do_nothing;
3158 /* Set the unwind-protect entry COUNT so that it invokes FUNC (ARG).
3159 It need not be at the top of the stack. Discard the entry's
3160 previous value without invoking it. */
3162 void
3163 set_unwind_protect (ptrdiff_t count, void (*func) (Lisp_Object),
3164 Lisp_Object arg)
3166 union specbinding *p = specpdl + count;
3167 p->unwind.kind = SPECPDL_UNWIND;
3168 p->unwind.func = func;
3169 p->unwind.arg = arg;
3172 void
3173 set_unwind_protect_ptr (ptrdiff_t count, void (*func) (void *), void *arg)
3175 union specbinding *p = specpdl + count;
3176 p->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3177 p->unwind_ptr.func = func;
3178 p->unwind_ptr.arg = arg;
3181 /* Pop and execute entries from the unwind-protect stack until the
3182 depth COUNT is reached. Return VALUE. */
3184 Lisp_Object
3185 unbind_to (ptrdiff_t count, Lisp_Object value)
3187 Lisp_Object quitf = Vquit_flag;
3188 struct gcpro gcpro1, gcpro2;
3190 GCPRO2 (value, quitf);
3191 Vquit_flag = Qnil;
3193 while (specpdl_ptr != specpdl + count)
3195 /* Decrement specpdl_ptr before we do the work to unbind it, so
3196 that an error in unbinding won't try to unbind the same entry
3197 again. Take care to copy any parts of the binding needed
3198 before invoking any code that can make more bindings. */
3200 specpdl_ptr--;
3202 switch (specpdl_ptr->kind)
3204 case SPECPDL_UNWIND:
3205 specpdl_ptr->unwind.func (specpdl_ptr->unwind.arg);
3206 break;
3207 case SPECPDL_UNWIND_PTR:
3208 specpdl_ptr->unwind_ptr.func (specpdl_ptr->unwind_ptr.arg);
3209 break;
3210 case SPECPDL_UNWIND_INT:
3211 specpdl_ptr->unwind_int.func (specpdl_ptr->unwind_int.arg);
3212 break;
3213 case SPECPDL_UNWIND_VOID:
3214 specpdl_ptr->unwind_void.func ();
3215 break;
3216 case SPECPDL_BACKTRACE:
3217 break;
3218 case SPECPDL_LET:
3219 { /* If variable has a trivial value (no forwarding), we can
3220 just set it. No need to check for constant symbols here,
3221 since that was already done by specbind. */
3222 struct Lisp_Symbol *sym = XSYMBOL (specpdl_symbol (specpdl_ptr));
3223 if (sym->redirect == SYMBOL_PLAINVAL)
3225 SET_SYMBOL_VAL (sym, specpdl_old_value (specpdl_ptr));
3226 break;
3228 else
3229 { /* FALLTHROUGH!!
3230 NOTE: we only ever come here if make_local_foo was used for
3231 the first time on this var within this let. */
3234 case SPECPDL_LET_DEFAULT:
3235 Fset_default (specpdl_symbol (specpdl_ptr),
3236 specpdl_old_value (specpdl_ptr));
3237 break;
3238 case SPECPDL_LET_LOCAL:
3240 Lisp_Object symbol = specpdl_symbol (specpdl_ptr);
3241 Lisp_Object where = specpdl_where (specpdl_ptr);
3242 Lisp_Object old_value = specpdl_old_value (specpdl_ptr);
3243 eassert (BUFFERP (where));
3245 /* If this was a local binding, reset the value in the appropriate
3246 buffer, but only if that buffer's binding still exists. */
3247 if (!NILP (Flocal_variable_p (symbol, where)))
3248 set_internal (symbol, old_value, where, 1);
3250 break;
3254 if (NILP (Vquit_flag) && !NILP (quitf))
3255 Vquit_flag = quitf;
3257 UNGCPRO;
3258 return value;
3261 DEFUN ("special-variable-p", Fspecial_variable_p, Sspecial_variable_p, 1, 1, 0,
3262 doc: /* Return non-nil if SYMBOL's global binding has been declared special.
3263 A special variable is one that will be bound dynamically, even in a
3264 context where binding is lexical by default. */)
3265 (Lisp_Object symbol)
3267 CHECK_SYMBOL (symbol);
3268 return XSYMBOL (symbol)->declared_special ? Qt : Qnil;
3272 DEFUN ("backtrace-debug", Fbacktrace_debug, Sbacktrace_debug, 2, 2, 0,
3273 doc: /* Set the debug-on-exit flag of eval frame LEVEL levels down to FLAG.
3274 The debugger is entered when that frame exits, if the flag is non-nil. */)
3275 (Lisp_Object level, Lisp_Object flag)
3277 union specbinding *pdl = backtrace_top ();
3278 register EMACS_INT i;
3280 CHECK_NUMBER (level);
3282 for (i = 0; backtrace_p (pdl) && i < XINT (level); i++)
3283 pdl = backtrace_next (pdl);
3285 if (backtrace_p (pdl))
3286 set_backtrace_debug_on_exit (pdl, !NILP (flag));
3288 return flag;
3291 DEFUN ("backtrace", Fbacktrace, Sbacktrace, 0, 0, "",
3292 doc: /* Print a trace of Lisp function calls currently active.
3293 Output stream used is value of `standard-output'. */)
3294 (void)
3296 union specbinding *pdl = backtrace_top ();
3297 Lisp_Object tem;
3298 Lisp_Object old_print_level = Vprint_level;
3300 if (NILP (Vprint_level))
3301 XSETFASTINT (Vprint_level, 8);
3303 while (backtrace_p (pdl))
3305 write_string (backtrace_debug_on_exit (pdl) ? "* " : " ", 2);
3306 if (backtrace_nargs (pdl) == UNEVALLED)
3308 Fprin1 (Fcons (backtrace_function (pdl), *backtrace_args (pdl)),
3309 Qnil);
3310 write_string ("\n", -1);
3312 else
3314 tem = backtrace_function (pdl);
3315 Fprin1 (tem, Qnil); /* This can QUIT. */
3316 write_string ("(", -1);
3318 ptrdiff_t i;
3319 for (i = 0; i < backtrace_nargs (pdl); i++)
3321 if (i) write_string (" ", -1);
3322 Fprin1 (backtrace_args (pdl)[i], Qnil);
3325 write_string (")\n", -1);
3327 pdl = backtrace_next (pdl);
3330 Vprint_level = old_print_level;
3331 return Qnil;
3334 static union specbinding *
3335 get_backtrace_frame (Lisp_Object nframes, Lisp_Object base)
3337 union specbinding *pdl = backtrace_top ();
3338 register EMACS_INT i;
3340 CHECK_NATNUM (nframes);
3342 if (!NILP (base))
3343 { /* Skip up to `base'. */
3344 base = Findirect_function (base, Qt);
3345 while (backtrace_p (pdl)
3346 && !EQ (base, Findirect_function (backtrace_function (pdl), Qt)))
3347 pdl = backtrace_next (pdl);
3350 /* Find the frame requested. */
3351 for (i = XFASTINT (nframes); i > 0 && backtrace_p (pdl); i--)
3352 pdl = backtrace_next (pdl);
3354 return pdl;
3357 DEFUN ("backtrace-frame", Fbacktrace_frame, Sbacktrace_frame, 1, 2, NULL,
3358 doc: /* Return the function and arguments NFRAMES up from current execution point.
3359 If that frame has not evaluated the arguments yet (or is a special form),
3360 the value is (nil FUNCTION ARG-FORMS...).
3361 If that frame has evaluated its arguments and called its function already,
3362 the value is (t FUNCTION ARG-VALUES...).
3363 A &rest arg is represented as the tail of the list ARG-VALUES.
3364 FUNCTION is whatever was supplied as car of evaluated list,
3365 or a lambda expression for macro calls.
3366 If NFRAMES is more than the number of frames, the value is nil.
3367 If BASE is non-nil, it should be a function and NFRAMES counts from its
3368 nearest activation frame. */)
3369 (Lisp_Object nframes, Lisp_Object base)
3371 union specbinding *pdl = get_backtrace_frame (nframes, base);
3373 if (!backtrace_p (pdl))
3374 return Qnil;
3375 if (backtrace_nargs (pdl) == UNEVALLED)
3376 return Fcons (Qnil,
3377 Fcons (backtrace_function (pdl), *backtrace_args (pdl)));
3378 else
3380 Lisp_Object tem = Flist (backtrace_nargs (pdl), backtrace_args (pdl));
3382 return Fcons (Qt, Fcons (backtrace_function (pdl), tem));
3386 /* For backtrace-eval, we want to temporarily unwind the last few elements of
3387 the specpdl stack, and then rewind them. We store the pre-unwind values
3388 directly in the pre-existing specpdl elements (i.e. we swap the current
3389 value and the old value stored in the specpdl), kind of like the inplace
3390 pointer-reversal trick. As it turns out, the rewind does the same as the
3391 unwind, except it starts from the other end of the specpdl stack, so we use
3392 the same function for both unwind and rewind. */
3393 static void
3394 backtrace_eval_unrewind (int distance)
3396 union specbinding *tmp = specpdl_ptr;
3397 int step = -1;
3398 if (distance < 0)
3399 { /* It's a rewind rather than unwind. */
3400 tmp += distance - 1;
3401 step = 1;
3402 distance = -distance;
3405 for (; distance > 0; distance--)
3407 tmp += step;
3408 /* */
3409 switch (tmp->kind)
3411 /* FIXME: Ideally we'd like to "temporarily unwind" (some of) those
3412 unwind_protect, but the problem is that we don't know how to
3413 rewind them afterwards. */
3414 case SPECPDL_UNWIND:
3416 Lisp_Object oldarg = tmp->unwind.arg;
3417 if (tmp->unwind.func == set_buffer_if_live)
3418 tmp->unwind.arg = Fcurrent_buffer ();
3419 else if (tmp->unwind.func == save_excursion_restore)
3420 tmp->unwind.arg = save_excursion_save ();
3421 else
3422 break;
3423 tmp->unwind.func (oldarg);
3424 break;
3427 case SPECPDL_UNWIND_PTR:
3428 case SPECPDL_UNWIND_INT:
3429 case SPECPDL_UNWIND_VOID:
3430 case SPECPDL_BACKTRACE:
3431 break;
3432 case SPECPDL_LET:
3433 { /* If variable has a trivial value (no forwarding), we can
3434 just set it. No need to check for constant symbols here,
3435 since that was already done by specbind. */
3436 struct Lisp_Symbol *sym = XSYMBOL (specpdl_symbol (tmp));
3437 if (sym->redirect == SYMBOL_PLAINVAL)
3439 Lisp_Object old_value = specpdl_old_value (tmp);
3440 set_specpdl_old_value (tmp, SYMBOL_VAL (sym));
3441 SET_SYMBOL_VAL (sym, old_value);
3442 break;
3444 else
3445 { /* FALLTHROUGH!!
3446 NOTE: we only ever come here if make_local_foo was used for
3447 the first time on this var within this let. */
3450 case SPECPDL_LET_DEFAULT:
3452 Lisp_Object sym = specpdl_symbol (tmp);
3453 Lisp_Object old_value = specpdl_old_value (tmp);
3454 set_specpdl_old_value (tmp, Fdefault_value (sym));
3455 Fset_default (sym, old_value);
3457 break;
3458 case SPECPDL_LET_LOCAL:
3460 Lisp_Object symbol = specpdl_symbol (tmp);
3461 Lisp_Object where = specpdl_where (tmp);
3462 Lisp_Object old_value = specpdl_old_value (tmp);
3463 eassert (BUFFERP (where));
3465 /* If this was a local binding, reset the value in the appropriate
3466 buffer, but only if that buffer's binding still exists. */
3467 if (!NILP (Flocal_variable_p (symbol, where)))
3469 set_specpdl_old_value
3470 (tmp, Fbuffer_local_value (symbol, where));
3471 set_internal (symbol, old_value, where, 1);
3474 break;
3479 DEFUN ("backtrace-eval", Fbacktrace_eval, Sbacktrace_eval, 2, 3, NULL,
3480 doc: /* Evaluate EXP in the context of some activation frame.
3481 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3482 (Lisp_Object exp, Lisp_Object nframes, Lisp_Object base)
3484 union specbinding *pdl = get_backtrace_frame (nframes, base);
3485 ptrdiff_t count = SPECPDL_INDEX ();
3486 ptrdiff_t distance = specpdl_ptr - pdl;
3487 eassert (distance >= 0);
3489 if (!backtrace_p (pdl))
3490 error ("Activation frame not found!");
3492 backtrace_eval_unrewind (distance);
3493 record_unwind_protect_int (backtrace_eval_unrewind, -distance);
3495 /* Use eval_sub rather than Feval since the main motivation behind
3496 backtrace-eval is to be able to get/set the value of lexical variables
3497 from the debugger. */
3498 return unbind_to (count, eval_sub (exp));
3501 DEFUN ("backtrace--locals", Fbacktrace__locals, Sbacktrace__locals, 1, 2, NULL,
3502 doc: /* Return names and values of local variables of a stack frame.
3503 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3504 (Lisp_Object nframes, Lisp_Object base)
3506 union specbinding *frame = get_backtrace_frame (nframes, base);
3507 union specbinding *prevframe
3508 = get_backtrace_frame (make_number (XFASTINT (nframes) - 1), base);
3509 ptrdiff_t distance = specpdl_ptr - frame;
3510 Lisp_Object result = Qnil;
3511 eassert (distance >= 0);
3513 if (!backtrace_p (prevframe))
3514 error ("Activation frame not found!");
3515 if (!backtrace_p (frame))
3516 error ("Activation frame not found!");
3518 /* The specpdl entries normally contain the symbol being bound along with its
3519 `old_value', so it can be restored. The new value to which it is bound is
3520 available in one of two places: either in the current value of the
3521 variable (if it hasn't been rebound yet) or in the `old_value' slot of the
3522 next specpdl entry for it.
3523 `backtrace_eval_unrewind' happens to swap the role of `old_value'
3524 and "new value", so we abuse it here, to fetch the new value.
3525 It's ugly (we'd rather not modify global data) and a bit inefficient,
3526 but it does the job for now. */
3527 backtrace_eval_unrewind (distance);
3529 /* Grab values. */
3531 union specbinding *tmp = prevframe;
3532 for (; tmp > frame; tmp--)
3534 switch (tmp->kind)
3536 case SPECPDL_LET:
3537 case SPECPDL_LET_DEFAULT:
3538 case SPECPDL_LET_LOCAL:
3540 Lisp_Object sym = specpdl_symbol (tmp);
3541 Lisp_Object val = specpdl_old_value (tmp);
3542 if (EQ (sym, Qinternal_interpreter_environment))
3544 Lisp_Object env = val;
3545 for (; CONSP (env); env = XCDR (env))
3547 Lisp_Object binding = XCAR (env);
3548 if (CONSP (binding))
3549 result = Fcons (Fcons (XCAR (binding),
3550 XCDR (binding)),
3551 result);
3554 else
3555 result = Fcons (Fcons (sym, val), result);
3561 /* Restore values from specpdl to original place. */
3562 backtrace_eval_unrewind (-distance);
3564 return result;
3568 void
3569 mark_specpdl (void)
3571 union specbinding *pdl;
3572 for (pdl = specpdl; pdl != specpdl_ptr; pdl++)
3574 switch (pdl->kind)
3576 case SPECPDL_UNWIND:
3577 mark_object (specpdl_arg (pdl));
3578 break;
3580 case SPECPDL_BACKTRACE:
3582 ptrdiff_t nargs = backtrace_nargs (pdl);
3583 mark_object (backtrace_function (pdl));
3584 if (nargs == UNEVALLED)
3585 nargs = 1;
3586 while (nargs--)
3587 mark_object (backtrace_args (pdl)[nargs]);
3589 break;
3591 case SPECPDL_LET_DEFAULT:
3592 case SPECPDL_LET_LOCAL:
3593 mark_object (specpdl_where (pdl));
3594 /* Fall through. */
3595 case SPECPDL_LET:
3596 mark_object (specpdl_symbol (pdl));
3597 mark_object (specpdl_old_value (pdl));
3598 break;
3603 void
3604 get_backtrace (Lisp_Object array)
3606 union specbinding *pdl = backtrace_next (backtrace_top ());
3607 ptrdiff_t i = 0, asize = ASIZE (array);
3609 /* Copy the backtrace contents into working memory. */
3610 for (; i < asize; i++)
3612 if (backtrace_p (pdl))
3614 ASET (array, i, backtrace_function (pdl));
3615 pdl = backtrace_next (pdl);
3617 else
3618 ASET (array, i, Qnil);
3622 Lisp_Object backtrace_top_function (void)
3624 union specbinding *pdl = backtrace_top ();
3625 return (backtrace_p (pdl) ? backtrace_function (pdl) : Qnil);
3628 void
3629 syms_of_eval (void)
3631 DEFVAR_INT ("max-specpdl-size", max_specpdl_size,
3632 doc: /* Limit on number of Lisp variable bindings and `unwind-protect's.
3633 If Lisp code tries to increase the total number past this amount,
3634 an error is signaled.
3635 You can safely use a value considerably larger than the default value,
3636 if that proves inconveniently small. However, if you increase it too far,
3637 Emacs could run out of memory trying to make the stack bigger.
3638 Note that this limit may be silently increased by the debugger
3639 if `debug-on-error' or `debug-on-quit' is set. */);
3641 DEFVAR_INT ("max-lisp-eval-depth", max_lisp_eval_depth,
3642 doc: /* Limit on depth in `eval', `apply' and `funcall' before error.
3644 This limit serves to catch infinite recursions for you before they cause
3645 actual stack overflow in C, which would be fatal for Emacs.
3646 You can safely make it considerably larger than its default value,
3647 if that proves inconveniently small. However, if you increase it too far,
3648 Emacs could overflow the real C stack, and crash. */);
3650 DEFVAR_LISP ("quit-flag", Vquit_flag,
3651 doc: /* Non-nil causes `eval' to abort, unless `inhibit-quit' is non-nil.
3652 If the value is t, that means do an ordinary quit.
3653 If the value equals `throw-on-input', that means quit by throwing
3654 to the tag specified in `throw-on-input'; it's for handling `while-no-input'.
3655 Typing C-g sets `quit-flag' to t, regardless of `inhibit-quit',
3656 but `inhibit-quit' non-nil prevents anything from taking notice of that. */);
3657 Vquit_flag = Qnil;
3659 DEFVAR_LISP ("inhibit-quit", Vinhibit_quit,
3660 doc: /* Non-nil inhibits C-g quitting from happening immediately.
3661 Note that `quit-flag' will still be set by typing C-g,
3662 so a quit will be signaled as soon as `inhibit-quit' is nil.
3663 To prevent this happening, set `quit-flag' to nil
3664 before making `inhibit-quit' nil. */);
3665 Vinhibit_quit = Qnil;
3667 DEFSYM (Qinhibit_quit, "inhibit-quit");
3668 DEFSYM (Qautoload, "autoload");
3669 DEFSYM (Qinhibit_debugger, "inhibit-debugger");
3670 DEFSYM (Qmacro, "macro");
3671 DEFSYM (Qdeclare, "declare");
3673 /* Note that the process handling also uses Qexit, but we don't want
3674 to staticpro it twice, so we just do it here. */
3675 DEFSYM (Qexit, "exit");
3677 DEFSYM (Qinteractive, "interactive");
3678 DEFSYM (Qcommandp, "commandp");
3679 DEFSYM (Qand_rest, "&rest");
3680 DEFSYM (Qand_optional, "&optional");
3681 DEFSYM (Qclosure, "closure");
3682 DEFSYM (Qdebug, "debug");
3684 DEFVAR_LISP ("inhibit-debugger", Vinhibit_debugger,
3685 doc: /* Non-nil means never enter the debugger.
3686 Normally set while the debugger is already active, to avoid recursive
3687 invocations. */);
3688 Vinhibit_debugger = Qnil;
3690 DEFVAR_LISP ("debug-on-error", Vdebug_on_error,
3691 doc: /* Non-nil means enter debugger if an error is signaled.
3692 Does not apply to errors handled by `condition-case' or those
3693 matched by `debug-ignored-errors'.
3694 If the value is a list, an error only means to enter the debugger
3695 if one of its condition symbols appears in the list.
3696 When you evaluate an expression interactively, this variable
3697 is temporarily non-nil if `eval-expression-debug-on-error' is non-nil.
3698 The command `toggle-debug-on-error' toggles this.
3699 See also the variable `debug-on-quit' and `inhibit-debugger'. */);
3700 Vdebug_on_error = Qnil;
3702 DEFVAR_LISP ("debug-ignored-errors", Vdebug_ignored_errors,
3703 doc: /* List of errors for which the debugger should not be called.
3704 Each element may be a condition-name or a regexp that matches error messages.
3705 If any element applies to a given error, that error skips the debugger
3706 and just returns to top level.
3707 This overrides the variable `debug-on-error'.
3708 It does not apply to errors handled by `condition-case'. */);
3709 Vdebug_ignored_errors = Qnil;
3711 DEFVAR_BOOL ("debug-on-quit", debug_on_quit,
3712 doc: /* Non-nil means enter debugger if quit is signaled (C-g, for example).
3713 Does not apply if quit is handled by a `condition-case'. */);
3714 debug_on_quit = 0;
3716 DEFVAR_BOOL ("debug-on-next-call", debug_on_next_call,
3717 doc: /* Non-nil means enter debugger before next `eval', `apply' or `funcall'. */);
3719 DEFVAR_BOOL ("debugger-may-continue", debugger_may_continue,
3720 doc: /* Non-nil means debugger may continue execution.
3721 This is nil when the debugger is called under circumstances where it
3722 might not be safe to continue. */);
3723 debugger_may_continue = 1;
3725 DEFVAR_LISP ("debugger", Vdebugger,
3726 doc: /* Function to call to invoke debugger.
3727 If due to frame exit, args are `exit' and the value being returned;
3728 this function's value will be returned instead of that.
3729 If due to error, args are `error' and a list of the args to `signal'.
3730 If due to `apply' or `funcall' entry, one arg, `lambda'.
3731 If due to `eval' entry, one arg, t. */);
3732 Vdebugger = Qnil;
3734 DEFVAR_LISP ("signal-hook-function", Vsignal_hook_function,
3735 doc: /* If non-nil, this is a function for `signal' to call.
3736 It receives the same arguments that `signal' was given.
3737 The Edebug package uses this to regain control. */);
3738 Vsignal_hook_function = Qnil;
3740 DEFVAR_LISP ("debug-on-signal", Vdebug_on_signal,
3741 doc: /* Non-nil means call the debugger regardless of condition handlers.
3742 Note that `debug-on-error', `debug-on-quit' and friends
3743 still determine whether to handle the particular condition. */);
3744 Vdebug_on_signal = Qnil;
3746 /* When lexical binding is being used,
3747 Vinternal_interpreter_environment is non-nil, and contains an alist
3748 of lexically-bound variable, or (t), indicating an empty
3749 environment. The lisp name of this variable would be
3750 `internal-interpreter-environment' if it weren't hidden.
3751 Every element of this list can be either a cons (VAR . VAL)
3752 specifying a lexical binding, or a single symbol VAR indicating
3753 that this variable should use dynamic scoping. */
3754 DEFSYM (Qinternal_interpreter_environment,
3755 "internal-interpreter-environment");
3756 DEFVAR_LISP ("internal-interpreter-environment",
3757 Vinternal_interpreter_environment,
3758 doc: /* If non-nil, the current lexical environment of the lisp interpreter.
3759 When lexical binding is not being used, this variable is nil.
3760 A value of `(t)' indicates an empty environment, otherwise it is an
3761 alist of active lexical bindings. */);
3762 Vinternal_interpreter_environment = Qnil;
3763 /* Don't export this variable to Elisp, so no one can mess with it
3764 (Just imagine if someone makes it buffer-local). */
3765 Funintern (Qinternal_interpreter_environment, Qnil);
3767 DEFSYM (Vrun_hooks, "run-hooks");
3769 staticpro (&Vautoload_queue);
3770 Vautoload_queue = Qnil;
3771 staticpro (&Vsignaling_function);
3772 Vsignaling_function = Qnil;
3774 inhibit_lisp_code = Qnil;
3776 defsubr (&Sor);
3777 defsubr (&Sand);
3778 defsubr (&Sif);
3779 defsubr (&Scond);
3780 defsubr (&Sprogn);
3781 defsubr (&Sprog1);
3782 defsubr (&Sprog2);
3783 defsubr (&Ssetq);
3784 defsubr (&Squote);
3785 defsubr (&Sfunction);
3786 defsubr (&Sdefault_toplevel_value);
3787 defsubr (&Sset_default_toplevel_value);
3788 defsubr (&Sdefvar);
3789 defsubr (&Sdefvaralias);
3790 defsubr (&Sdefconst);
3791 defsubr (&Smake_var_non_special);
3792 defsubr (&Slet);
3793 defsubr (&SletX);
3794 defsubr (&Swhile);
3795 defsubr (&Smacroexpand);
3796 defsubr (&Scatch);
3797 defsubr (&Sthrow);
3798 defsubr (&Sunwind_protect);
3799 defsubr (&Scondition_case);
3800 defsubr (&Ssignal);
3801 defsubr (&Scommandp);
3802 defsubr (&Sautoload);
3803 defsubr (&Sautoload_do_load);
3804 defsubr (&Seval);
3805 defsubr (&Sapply);
3806 defsubr (&Sfuncall);
3807 defsubr (&Srun_hooks);
3808 defsubr (&Srun_hook_with_args);
3809 defsubr (&Srun_hook_with_args_until_success);
3810 defsubr (&Srun_hook_with_args_until_failure);
3811 defsubr (&Srun_hook_wrapped);
3812 defsubr (&Sfetch_bytecode);
3813 defsubr (&Sbacktrace_debug);
3814 defsubr (&Sbacktrace);
3815 defsubr (&Sbacktrace_frame);
3816 defsubr (&Sbacktrace_eval);
3817 defsubr (&Sbacktrace__locals);
3818 defsubr (&Sspecial_variable_p);
3819 defsubr (&Sfunctionp);