]> code.delx.au - gnu-emacs/blob - src/eval.c
Simplify push_handler and profile its malloc
[gnu-emacs] / src / eval.c
1 /* Evaluator for GNU Emacs Lisp interpreter.
2
3 Copyright (C) 1985-1987, 1993-1995, 1999-2015 Free Software Foundation,
4 Inc.
5
6 This file is part of GNU Emacs.
7
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.
12
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.
17
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/>. */
20
21
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"
31
32 /* Chain of condition and catch handlers currently in effect. */
33
34 struct handler *handlerlist;
35
36 /* Non-nil means record all fset's and provide's, to be undone
37 if the file being autoloaded is not fully loaded.
38 They are recorded by being consed onto the front of Vautoload_queue:
39 (FUN . ODEF) for a defun, (0 . OFEATURES) for a provide. */
40
41 Lisp_Object Vautoload_queue;
42
43 /* This holds either the symbol `run-hooks' or nil.
44 It is nil at an early stage of startup, and when Emacs
45 is shutting down. */
46 Lisp_Object Vrun_hooks;
47
48 /* Current number of specbindings allocated in specpdl, not counting
49 the dummy entry specpdl[-1]. */
50
51 ptrdiff_t specpdl_size;
52
53 /* Pointer to beginning of specpdl. A dummy entry specpdl[-1] exists
54 only so that its address can be taken. */
55
56 union specbinding *specpdl;
57
58 /* Pointer to first unused element in specpdl. */
59
60 union specbinding *specpdl_ptr;
61
62 /* Depth in Lisp evaluations and function calls. */
63
64 static EMACS_INT lisp_eval_depth;
65
66 /* The value of num_nonmacro_input_events as of the last time we
67 started to enter the debugger. If we decide to enter the debugger
68 again when this is still equal to num_nonmacro_input_events, then we
69 know that the debugger itself has an error, and we should just
70 signal the error instead of entering an infinite loop of debugger
71 invocations. */
72
73 static EMACS_INT when_entered_debugger;
74
75 /* The function from which the last `signal' was called. Set in
76 Fsignal. */
77 /* FIXME: We should probably get rid of this! */
78 Lisp_Object Vsignaling_function;
79
80 /* If non-nil, Lisp code must not be run since some part of Emacs is in
81 an inconsistent state. Currently unused. */
82 Lisp_Object inhibit_lisp_code;
83
84 /* These would ordinarily be static, but they need to be visible to GDB. */
85 bool backtrace_p (union specbinding *) EXTERNALLY_VISIBLE;
86 Lisp_Object *backtrace_args (union specbinding *) EXTERNALLY_VISIBLE;
87 Lisp_Object backtrace_function (union specbinding *) EXTERNALLY_VISIBLE;
88 union specbinding *backtrace_next (union specbinding *) EXTERNALLY_VISIBLE;
89 union specbinding *backtrace_top (void) EXTERNALLY_VISIBLE;
90
91 static Lisp_Object funcall_lambda (Lisp_Object, ptrdiff_t, Lisp_Object *);
92 static Lisp_Object apply_lambda (Lisp_Object, Lisp_Object, ptrdiff_t);
93
94 static Lisp_Object
95 specpdl_symbol (union specbinding *pdl)
96 {
97 eassert (pdl->kind >= SPECPDL_LET);
98 return pdl->let.symbol;
99 }
100
101 static Lisp_Object
102 specpdl_old_value (union specbinding *pdl)
103 {
104 eassert (pdl->kind >= SPECPDL_LET);
105 return pdl->let.old_value;
106 }
107
108 static void
109 set_specpdl_old_value (union specbinding *pdl, Lisp_Object val)
110 {
111 eassert (pdl->kind >= SPECPDL_LET);
112 pdl->let.old_value = val;
113 }
114
115 static Lisp_Object
116 specpdl_where (union specbinding *pdl)
117 {
118 eassert (pdl->kind > SPECPDL_LET);
119 return pdl->let.where;
120 }
121
122 static Lisp_Object
123 specpdl_arg (union specbinding *pdl)
124 {
125 eassert (pdl->kind == SPECPDL_UNWIND);
126 return pdl->unwind.arg;
127 }
128
129 Lisp_Object
130 backtrace_function (union specbinding *pdl)
131 {
132 eassert (pdl->kind == SPECPDL_BACKTRACE);
133 return pdl->bt.function;
134 }
135
136 static ptrdiff_t
137 backtrace_nargs (union specbinding *pdl)
138 {
139 eassert (pdl->kind == SPECPDL_BACKTRACE);
140 return pdl->bt.nargs;
141 }
142
143 Lisp_Object *
144 backtrace_args (union specbinding *pdl)
145 {
146 eassert (pdl->kind == SPECPDL_BACKTRACE);
147 return pdl->bt.args;
148 }
149
150 static bool
151 backtrace_debug_on_exit (union specbinding *pdl)
152 {
153 eassert (pdl->kind == SPECPDL_BACKTRACE);
154 return pdl->bt.debug_on_exit;
155 }
156
157 /* Functions to modify slots of backtrace records. */
158
159 static void
160 set_backtrace_args (union specbinding *pdl, Lisp_Object *args, ptrdiff_t nargs)
161 {
162 eassert (pdl->kind == SPECPDL_BACKTRACE);
163 pdl->bt.args = args;
164 pdl->bt.nargs = nargs;
165 }
166
167 static void
168 set_backtrace_debug_on_exit (union specbinding *pdl, bool doe)
169 {
170 eassert (pdl->kind == SPECPDL_BACKTRACE);
171 pdl->bt.debug_on_exit = doe;
172 }
173
174 /* Helper functions to scan the backtrace. */
175
176 bool
177 backtrace_p (union specbinding *pdl)
178 { return pdl >= specpdl; }
179
180 union specbinding *
181 backtrace_top (void)
182 {
183 union specbinding *pdl = specpdl_ptr - 1;
184 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
185 pdl--;
186 return pdl;
187 }
188
189 union specbinding *
190 backtrace_next (union specbinding *pdl)
191 {
192 pdl--;
193 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
194 pdl--;
195 return pdl;
196 }
197
198 /* Return a pointer to somewhere near the top of the C stack. */
199 void *
200 near_C_stack_top (void)
201 {
202 return backtrace_args (backtrace_top ());
203 }
204
205 void
206 init_eval_once (void)
207 {
208 enum { size = 50 };
209 union specbinding *pdlvec = xmalloc ((size + 1) * sizeof *specpdl);
210 specpdl_size = size;
211 specpdl = specpdl_ptr = pdlvec + 1;
212 /* Don't forget to update docs (lispref node "Local Variables"). */
213 max_specpdl_size = 1300; /* 1000 is not enough for CEDET's c-by.el. */
214 max_lisp_eval_depth = 800;
215
216 Vrun_hooks = Qnil;
217 }
218
219 static struct handler handlerlist_sentinel;
220
221 void
222 init_eval (void)
223 {
224 byte_stack_list = 0;
225 specpdl_ptr = specpdl;
226 { /* Put a dummy catcher at top-level so that handlerlist is never NULL.
227 This is important since handlerlist->nextfree holds the freelist
228 which would otherwise leak every time we unwind back to top-level. */
229 handlerlist = handlerlist_sentinel.nextfree = &handlerlist_sentinel;
230 struct handler *c = push_handler (Qunbound, CATCHER);
231 eassert (c == &handlerlist_sentinel);
232 handlerlist_sentinel.nextfree = NULL;
233 handlerlist_sentinel.next = NULL;
234 }
235 Vquit_flag = Qnil;
236 debug_on_next_call = 0;
237 lisp_eval_depth = 0;
238 /* This is less than the initial value of num_nonmacro_input_events. */
239 when_entered_debugger = -1;
240 }
241
242 /* Unwind-protect function used by call_debugger. */
243
244 static void
245 restore_stack_limits (Lisp_Object data)
246 {
247 max_specpdl_size = XINT (XCAR (data));
248 max_lisp_eval_depth = XINT (XCDR (data));
249 }
250
251 static void grow_specpdl (void);
252
253 /* Call the Lisp debugger, giving it argument ARG. */
254
255 Lisp_Object
256 call_debugger (Lisp_Object arg)
257 {
258 bool debug_while_redisplaying;
259 ptrdiff_t count = SPECPDL_INDEX ();
260 Lisp_Object val;
261 EMACS_INT old_depth = max_lisp_eval_depth;
262 /* Do not allow max_specpdl_size less than actual depth (Bug#16603). */
263 EMACS_INT old_max = max (max_specpdl_size, count);
264
265 if (lisp_eval_depth + 40 > max_lisp_eval_depth)
266 max_lisp_eval_depth = lisp_eval_depth + 40;
267
268 /* While debugging Bug#16603, previous value of 100 was found
269 too small to avoid specpdl overflow in the debugger itself. */
270 if (max_specpdl_size - 200 < count)
271 max_specpdl_size = count + 200;
272
273 if (old_max == count)
274 {
275 /* We can enter the debugger due to specpdl overflow (Bug#16603). */
276 specpdl_ptr--;
277 grow_specpdl ();
278 }
279
280 /* Restore limits after leaving the debugger. */
281 record_unwind_protect (restore_stack_limits,
282 Fcons (make_number (old_max),
283 make_number (old_depth)));
284
285 #ifdef HAVE_WINDOW_SYSTEM
286 if (display_hourglass_p)
287 cancel_hourglass ();
288 #endif
289
290 debug_on_next_call = 0;
291 when_entered_debugger = num_nonmacro_input_events;
292
293 /* Resetting redisplaying_p to 0 makes sure that debug output is
294 displayed if the debugger is invoked during redisplay. */
295 debug_while_redisplaying = redisplaying_p;
296 redisplaying_p = 0;
297 specbind (intern ("debugger-may-continue"),
298 debug_while_redisplaying ? Qnil : Qt);
299 specbind (Qinhibit_redisplay, Qnil);
300 specbind (Qinhibit_debugger, Qt);
301
302 #if 0 /* Binding this prevents execution of Lisp code during
303 redisplay, which necessarily leads to display problems. */
304 specbind (Qinhibit_eval_during_redisplay, Qt);
305 #endif
306
307 val = apply1 (Vdebugger, arg);
308
309 /* Interrupting redisplay and resuming it later is not safe under
310 all circumstances. So, when the debugger returns, abort the
311 interrupted redisplay by going back to the top-level. */
312 if (debug_while_redisplaying)
313 Ftop_level ();
314
315 return unbind_to (count, val);
316 }
317
318 static void
319 do_debug_on_call (Lisp_Object code, ptrdiff_t count)
320 {
321 debug_on_next_call = 0;
322 set_backtrace_debug_on_exit (specpdl + count, true);
323 call_debugger (list1 (code));
324 }
325 \f
326 /* NOTE!!! Every function that can call EVAL must protect its args
327 and temporaries from garbage collection while it needs them.
328 The definition of `For' shows what you have to do. */
329
330 DEFUN ("or", For, Sor, 0, UNEVALLED, 0,
331 doc: /* Eval args until one of them yields non-nil, then return that value.
332 The remaining args are not evalled at all.
333 If all args return nil, return nil.
334 usage: (or CONDITIONS...) */)
335 (Lisp_Object args)
336 {
337 Lisp_Object val = Qnil;
338
339 while (CONSP (args))
340 {
341 val = eval_sub (XCAR (args));
342 if (!NILP (val))
343 break;
344 args = XCDR (args);
345 }
346
347 return val;
348 }
349
350 DEFUN ("and", Fand, Sand, 0, UNEVALLED, 0,
351 doc: /* Eval args until one of them yields nil, then return nil.
352 The remaining args are not evalled at all.
353 If no arg yields nil, return the last arg's value.
354 usage: (and CONDITIONS...) */)
355 (Lisp_Object args)
356 {
357 Lisp_Object val = Qt;
358
359 while (CONSP (args))
360 {
361 val = eval_sub (XCAR (args));
362 if (NILP (val))
363 break;
364 args = XCDR (args);
365 }
366
367 return val;
368 }
369
370 DEFUN ("if", Fif, Sif, 2, UNEVALLED, 0,
371 doc: /* If COND yields non-nil, do THEN, else do ELSE...
372 Returns the value of THEN or the value of the last of the ELSE's.
373 THEN must be one expression, but ELSE... can be zero or more expressions.
374 If COND yields nil, and there are no ELSE's, the value is nil.
375 usage: (if COND THEN ELSE...) */)
376 (Lisp_Object args)
377 {
378 Lisp_Object cond;
379
380 cond = eval_sub (XCAR (args));
381
382 if (!NILP (cond))
383 return eval_sub (Fcar (XCDR (args)));
384 return Fprogn (XCDR (XCDR (args)));
385 }
386
387 DEFUN ("cond", Fcond, Scond, 0, UNEVALLED, 0,
388 doc: /* Try each clause until one succeeds.
389 Each clause looks like (CONDITION BODY...). CONDITION is evaluated
390 and, if the value is non-nil, this clause succeeds:
391 then the expressions in BODY are evaluated and the last one's
392 value is the value of the cond-form.
393 If a clause has one element, as in (CONDITION), then the cond-form
394 returns CONDITION's value, if that is non-nil.
395 If no clause succeeds, cond returns nil.
396 usage: (cond CLAUSES...) */)
397 (Lisp_Object args)
398 {
399 Lisp_Object val = args;
400
401 while (CONSP (args))
402 {
403 Lisp_Object clause = XCAR (args);
404 val = eval_sub (Fcar (clause));
405 if (!NILP (val))
406 {
407 if (!NILP (XCDR (clause)))
408 val = Fprogn (XCDR (clause));
409 break;
410 }
411 args = XCDR (args);
412 }
413
414 return val;
415 }
416
417 DEFUN ("progn", Fprogn, Sprogn, 0, UNEVALLED, 0,
418 doc: /* Eval BODY forms sequentially and return value of last one.
419 usage: (progn BODY...) */)
420 (Lisp_Object body)
421 {
422 Lisp_Object val = Qnil;
423
424 while (CONSP (body))
425 {
426 val = eval_sub (XCAR (body));
427 body = XCDR (body);
428 }
429
430 return val;
431 }
432
433 /* Evaluate BODY sequentially, discarding its value. Suitable for
434 record_unwind_protect. */
435
436 void
437 unwind_body (Lisp_Object body)
438 {
439 Fprogn (body);
440 }
441
442 DEFUN ("prog1", Fprog1, Sprog1, 1, UNEVALLED, 0,
443 doc: /* Eval FIRST and BODY sequentially; return value from FIRST.
444 The value of FIRST is saved during the evaluation of the remaining args,
445 whose values are discarded.
446 usage: (prog1 FIRST BODY...) */)
447 (Lisp_Object args)
448 {
449 Lisp_Object val;
450 Lisp_Object args_left;
451
452 args_left = args;
453 val = args;
454
455 val = eval_sub (XCAR (args_left));
456 while (CONSP (args_left = XCDR (args_left)))
457 eval_sub (XCAR (args_left));
458
459 return val;
460 }
461
462 DEFUN ("prog2", Fprog2, Sprog2, 2, UNEVALLED, 0,
463 doc: /* Eval FORM1, FORM2 and BODY sequentially; return value from FORM2.
464 The value of FORM2 is saved during the evaluation of the
465 remaining args, whose values are discarded.
466 usage: (prog2 FORM1 FORM2 BODY...) */)
467 (Lisp_Object args)
468 {
469 eval_sub (XCAR (args));
470 return Fprog1 (XCDR (args));
471 }
472
473 DEFUN ("setq", Fsetq, Ssetq, 0, UNEVALLED, 0,
474 doc: /* Set each SYM to the value of its VAL.
475 The symbols SYM are variables; they are literal (not evaluated).
476 The values VAL are expressions; they are evaluated.
477 Thus, (setq x (1+ y)) sets `x' to the value of `(1+ y)'.
478 The second VAL is not computed until after the first SYM is set, and so on;
479 each VAL can use the new value of variables set earlier in the `setq'.
480 The return value of the `setq' form is the value of the last VAL.
481 usage: (setq [SYM VAL]...) */)
482 (Lisp_Object args)
483 {
484 Lisp_Object val, sym, lex_binding;
485
486 val = args;
487 if (CONSP (args))
488 {
489 Lisp_Object args_left = args;
490
491 do
492 {
493 val = eval_sub (Fcar (XCDR (args_left)));
494 sym = XCAR (args_left);
495
496 /* Like for eval_sub, we do not check declared_special here since
497 it's been done when let-binding. */
498 if (!NILP (Vinternal_interpreter_environment) /* Mere optimization! */
499 && SYMBOLP (sym)
500 && !NILP (lex_binding
501 = Fassq (sym, Vinternal_interpreter_environment)))
502 XSETCDR (lex_binding, val); /* SYM is lexically bound. */
503 else
504 Fset (sym, val); /* SYM is dynamically bound. */
505
506 args_left = Fcdr (XCDR (args_left));
507 }
508 while (CONSP (args_left));
509 }
510
511 return val;
512 }
513
514 DEFUN ("quote", Fquote, Squote, 1, UNEVALLED, 0,
515 doc: /* Return the argument, without evaluating it. `(quote x)' yields `x'.
516 Warning: `quote' does not construct its return value, but just returns
517 the value that was pre-constructed by the Lisp reader (see info node
518 `(elisp)Printed Representation').
519 This means that \\='(a . b) is not identical to (cons \\='a \\='b): the former
520 does not cons. Quoting should be reserved for constants that will
521 never be modified by side-effects, unless you like self-modifying code.
522 See the common pitfall in info node `(elisp)Rearrangement' for an example
523 of unexpected results when a quoted object is modified.
524 usage: (quote ARG) */)
525 (Lisp_Object args)
526 {
527 if (CONSP (XCDR (args)))
528 xsignal2 (Qwrong_number_of_arguments, Qquote, Flength (args));
529 return XCAR (args);
530 }
531
532 DEFUN ("function", Ffunction, Sfunction, 1, UNEVALLED, 0,
533 doc: /* Like `quote', but preferred for objects which are functions.
534 In byte compilation, `function' causes its argument to be compiled.
535 `quote' cannot do that.
536 usage: (function ARG) */)
537 (Lisp_Object args)
538 {
539 Lisp_Object quoted = XCAR (args);
540
541 if (CONSP (XCDR (args)))
542 xsignal2 (Qwrong_number_of_arguments, Qfunction, Flength (args));
543
544 if (!NILP (Vinternal_interpreter_environment)
545 && CONSP (quoted)
546 && EQ (XCAR (quoted), Qlambda))
547 { /* This is a lambda expression within a lexical environment;
548 return an interpreted closure instead of a simple lambda. */
549 Lisp_Object cdr = XCDR (quoted);
550 Lisp_Object tmp = cdr;
551 if (CONSP (tmp)
552 && (tmp = XCDR (tmp), CONSP (tmp))
553 && (tmp = XCAR (tmp), CONSP (tmp))
554 && (EQ (QCdocumentation, XCAR (tmp))))
555 { /* Handle the special (:documentation <form>) to build the docstring
556 dynamically. */
557 Lisp_Object docstring = eval_sub (Fcar (XCDR (tmp)));
558 CHECK_STRING (docstring);
559 cdr = Fcons (XCAR (cdr), Fcons (docstring, XCDR (XCDR (cdr))));
560 }
561 return Fcons (Qclosure, Fcons (Vinternal_interpreter_environment,
562 cdr));
563 }
564 else
565 /* Simply quote the argument. */
566 return quoted;
567 }
568
569
570 DEFUN ("defvaralias", Fdefvaralias, Sdefvaralias, 2, 3, 0,
571 doc: /* Make NEW-ALIAS a variable alias for symbol BASE-VARIABLE.
572 Aliased variables always have the same value; setting one sets the other.
573 Third arg DOCSTRING, if non-nil, is documentation for NEW-ALIAS. If it is
574 omitted or nil, NEW-ALIAS gets the documentation string of BASE-VARIABLE,
575 or of the variable at the end of the chain of aliases, if BASE-VARIABLE is
576 itself an alias. If NEW-ALIAS is bound, and BASE-VARIABLE is not,
577 then the value of BASE-VARIABLE is set to that of NEW-ALIAS.
578 The return value is BASE-VARIABLE. */)
579 (Lisp_Object new_alias, Lisp_Object base_variable, Lisp_Object docstring)
580 {
581 struct Lisp_Symbol *sym;
582
583 CHECK_SYMBOL (new_alias);
584 CHECK_SYMBOL (base_variable);
585
586 sym = XSYMBOL (new_alias);
587
588 if (sym->constant)
589 /* Not sure why, but why not? */
590 error ("Cannot make a constant an alias");
591
592 switch (sym->redirect)
593 {
594 case SYMBOL_FORWARDED:
595 error ("Cannot make an internal variable an alias");
596 case SYMBOL_LOCALIZED:
597 error ("Don't know how to make a localized variable an alias");
598 case SYMBOL_PLAINVAL:
599 case SYMBOL_VARALIAS:
600 break;
601 default:
602 emacs_abort ();
603 }
604
605 /* http://lists.gnu.org/archive/html/emacs-devel/2008-04/msg00834.html
606 If n_a is bound, but b_v is not, set the value of b_v to n_a,
607 so that old-code that affects n_a before the aliasing is setup
608 still works. */
609 if (NILP (Fboundp (base_variable)))
610 set_internal (base_variable, find_symbol_value (new_alias), Qnil, 1);
611
612 {
613 union specbinding *p;
614
615 for (p = specpdl_ptr; p > specpdl; )
616 if ((--p)->kind >= SPECPDL_LET
617 && (EQ (new_alias, specpdl_symbol (p))))
618 error ("Don't know how to make a let-bound variable an alias");
619 }
620
621 sym->declared_special = 1;
622 XSYMBOL (base_variable)->declared_special = 1;
623 sym->redirect = SYMBOL_VARALIAS;
624 SET_SYMBOL_ALIAS (sym, XSYMBOL (base_variable));
625 sym->constant = SYMBOL_CONSTANT_P (base_variable);
626 LOADHIST_ATTACH (new_alias);
627 /* Even if docstring is nil: remove old docstring. */
628 Fput (new_alias, Qvariable_documentation, docstring);
629
630 return base_variable;
631 }
632
633 static union specbinding *
634 default_toplevel_binding (Lisp_Object symbol)
635 {
636 union specbinding *binding = NULL;
637 union specbinding *pdl = specpdl_ptr;
638 while (pdl > specpdl)
639 {
640 switch ((--pdl)->kind)
641 {
642 case SPECPDL_LET_DEFAULT:
643 case SPECPDL_LET:
644 if (EQ (specpdl_symbol (pdl), symbol))
645 binding = pdl;
646 break;
647
648 case SPECPDL_UNWIND:
649 case SPECPDL_UNWIND_PTR:
650 case SPECPDL_UNWIND_INT:
651 case SPECPDL_UNWIND_VOID:
652 case SPECPDL_BACKTRACE:
653 case SPECPDL_LET_LOCAL:
654 break;
655
656 default:
657 emacs_abort ();
658 }
659 }
660 return binding;
661 }
662
663 DEFUN ("default-toplevel-value", Fdefault_toplevel_value, Sdefault_toplevel_value, 1, 1, 0,
664 doc: /* Return SYMBOL's toplevel default value.
665 "Toplevel" means outside of any let binding. */)
666 (Lisp_Object symbol)
667 {
668 union specbinding *binding = default_toplevel_binding (symbol);
669 Lisp_Object value
670 = binding ? specpdl_old_value (binding) : Fdefault_value (symbol);
671 if (!EQ (value, Qunbound))
672 return value;
673 xsignal1 (Qvoid_variable, symbol);
674 }
675
676 DEFUN ("set-default-toplevel-value", Fset_default_toplevel_value,
677 Sset_default_toplevel_value, 2, 2, 0,
678 doc: /* Set SYMBOL's toplevel default value to VALUE.
679 "Toplevel" means outside of any let binding. */)
680 (Lisp_Object symbol, Lisp_Object value)
681 {
682 union specbinding *binding = default_toplevel_binding (symbol);
683 if (binding)
684 set_specpdl_old_value (binding, value);
685 else
686 Fset_default (symbol, value);
687 return Qnil;
688 }
689
690 DEFUN ("defvar", Fdefvar, Sdefvar, 1, UNEVALLED, 0,
691 doc: /* Define SYMBOL as a variable, and return SYMBOL.
692 You are not required to define a variable in order to use it, but
693 defining it lets you supply an initial value and documentation, which
694 can be referred to by the Emacs help facilities and other programming
695 tools. The `defvar' form also declares the variable as \"special\",
696 so that it is always dynamically bound even if `lexical-binding' is t.
697
698 The optional argument INITVALUE is evaluated, and used to set SYMBOL,
699 only if SYMBOL's value is void. If SYMBOL is buffer-local, its
700 default value is what is set; buffer-local values are not affected.
701 If INITVALUE is missing, SYMBOL's value is not set.
702
703 If SYMBOL has a local binding, then this form affects the local
704 binding. This is usually not what you want. Thus, if you need to
705 load a file defining variables, with this form or with `defconst' or
706 `defcustom', you should always load that file _outside_ any bindings
707 for these variables. (`defconst' and `defcustom' behave similarly in
708 this respect.)
709
710 The optional argument DOCSTRING is a documentation string for the
711 variable.
712
713 To define a user option, use `defcustom' instead of `defvar'.
714 usage: (defvar SYMBOL &optional INITVALUE DOCSTRING) */)
715 (Lisp_Object args)
716 {
717 Lisp_Object sym, tem, tail;
718
719 sym = XCAR (args);
720 tail = XCDR (args);
721
722 if (CONSP (tail))
723 {
724 if (CONSP (XCDR (tail)) && CONSP (XCDR (XCDR (tail))))
725 error ("Too many arguments");
726
727 tem = Fdefault_boundp (sym);
728
729 /* Do it before evaluating the initial value, for self-references. */
730 XSYMBOL (sym)->declared_special = 1;
731
732 if (NILP (tem))
733 Fset_default (sym, eval_sub (XCAR (tail)));
734 else
735 { /* Check if there is really a global binding rather than just a let
736 binding that shadows the global unboundness of the var. */
737 union specbinding *binding = default_toplevel_binding (sym);
738 if (binding && EQ (specpdl_old_value (binding), Qunbound))
739 {
740 set_specpdl_old_value (binding, eval_sub (XCAR (tail)));
741 }
742 }
743 tail = XCDR (tail);
744 tem = Fcar (tail);
745 if (!NILP (tem))
746 {
747 if (!NILP (Vpurify_flag))
748 tem = Fpurecopy (tem);
749 Fput (sym, Qvariable_documentation, tem);
750 }
751 LOADHIST_ATTACH (sym);
752 }
753 else if (!NILP (Vinternal_interpreter_environment)
754 && !XSYMBOL (sym)->declared_special)
755 /* A simple (defvar foo) with lexical scoping does "nothing" except
756 declare that var to be dynamically scoped *locally* (i.e. within
757 the current file or let-block). */
758 Vinternal_interpreter_environment
759 = Fcons (sym, Vinternal_interpreter_environment);
760 else
761 {
762 /* Simple (defvar <var>) should not count as a definition at all.
763 It could get in the way of other definitions, and unloading this
764 package could try to make the variable unbound. */
765 }
766
767 return sym;
768 }
769
770 DEFUN ("defconst", Fdefconst, Sdefconst, 2, UNEVALLED, 0,
771 doc: /* Define SYMBOL as a constant variable.
772 This declares that neither programs nor users should ever change the
773 value. This constancy is not actually enforced by Emacs Lisp, but
774 SYMBOL is marked as a special variable so that it is never lexically
775 bound.
776
777 The `defconst' form always sets the value of SYMBOL to the result of
778 evalling INITVALUE. If SYMBOL is buffer-local, its default value is
779 what is set; buffer-local values are not affected. If SYMBOL has a
780 local binding, then this form sets the local binding's value.
781 However, you should normally not make local bindings for variables
782 defined with this form.
783
784 The optional DOCSTRING specifies the variable's documentation string.
785 usage: (defconst SYMBOL INITVALUE [DOCSTRING]) */)
786 (Lisp_Object args)
787 {
788 Lisp_Object sym, tem;
789
790 sym = XCAR (args);
791 if (CONSP (Fcdr (XCDR (XCDR (args)))))
792 error ("Too many arguments");
793
794 tem = eval_sub (Fcar (XCDR (args)));
795 if (!NILP (Vpurify_flag))
796 tem = Fpurecopy (tem);
797 Fset_default (sym, tem);
798 XSYMBOL (sym)->declared_special = 1;
799 tem = Fcar (XCDR (XCDR (args)));
800 if (!NILP (tem))
801 {
802 if (!NILP (Vpurify_flag))
803 tem = Fpurecopy (tem);
804 Fput (sym, Qvariable_documentation, tem);
805 }
806 Fput (sym, Qrisky_local_variable, Qt);
807 LOADHIST_ATTACH (sym);
808 return sym;
809 }
810
811 /* Make SYMBOL lexically scoped. */
812 DEFUN ("internal-make-var-non-special", Fmake_var_non_special,
813 Smake_var_non_special, 1, 1, 0,
814 doc: /* Internal function. */)
815 (Lisp_Object symbol)
816 {
817 CHECK_SYMBOL (symbol);
818 XSYMBOL (symbol)->declared_special = 0;
819 return Qnil;
820 }
821
822 \f
823 DEFUN ("let*", FletX, SletX, 1, UNEVALLED, 0,
824 doc: /* Bind variables according to VARLIST then eval BODY.
825 The value of the last form in BODY is returned.
826 Each element of VARLIST is a symbol (which is bound to nil)
827 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
828 Each VALUEFORM can refer to the symbols already bound by this VARLIST.
829 usage: (let* VARLIST BODY...) */)
830 (Lisp_Object args)
831 {
832 Lisp_Object varlist, var, val, elt, lexenv;
833 ptrdiff_t count = SPECPDL_INDEX ();
834
835 lexenv = Vinternal_interpreter_environment;
836
837 varlist = XCAR (args);
838 while (CONSP (varlist))
839 {
840 QUIT;
841
842 elt = XCAR (varlist);
843 if (SYMBOLP (elt))
844 {
845 var = elt;
846 val = Qnil;
847 }
848 else if (! NILP (Fcdr (Fcdr (elt))))
849 signal_error ("`let' bindings can have only one value-form", elt);
850 else
851 {
852 var = Fcar (elt);
853 val = eval_sub (Fcar (Fcdr (elt)));
854 }
855
856 if (!NILP (lexenv) && SYMBOLP (var)
857 && !XSYMBOL (var)->declared_special
858 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
859 /* Lexically bind VAR by adding it to the interpreter's binding
860 alist. */
861 {
862 Lisp_Object newenv
863 = Fcons (Fcons (var, val), Vinternal_interpreter_environment);
864 if (EQ (Vinternal_interpreter_environment, lexenv))
865 /* Save the old lexical environment on the specpdl stack,
866 but only for the first lexical binding, since we'll never
867 need to revert to one of the intermediate ones. */
868 specbind (Qinternal_interpreter_environment, newenv);
869 else
870 Vinternal_interpreter_environment = newenv;
871 }
872 else
873 specbind (var, val);
874
875 varlist = XCDR (varlist);
876 }
877
878 val = Fprogn (XCDR (args));
879 return unbind_to (count, val);
880 }
881
882 DEFUN ("let", Flet, Slet, 1, UNEVALLED, 0,
883 doc: /* Bind variables according to VARLIST then eval BODY.
884 The value of the last form in BODY is returned.
885 Each element of VARLIST is a symbol (which is bound to nil)
886 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
887 All the VALUEFORMs are evalled before any symbols are bound.
888 usage: (let VARLIST BODY...) */)
889 (Lisp_Object args)
890 {
891 Lisp_Object *temps, tem, lexenv;
892 Lisp_Object elt, varlist;
893 ptrdiff_t count = SPECPDL_INDEX ();
894 ptrdiff_t argnum;
895 USE_SAFE_ALLOCA;
896
897 varlist = XCAR (args);
898
899 /* Make space to hold the values to give the bound variables. */
900 elt = Flength (varlist);
901 SAFE_ALLOCA_LISP (temps, XFASTINT (elt));
902
903 /* Compute the values and store them in `temps'. */
904
905 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
906 {
907 QUIT;
908 elt = XCAR (varlist);
909 if (SYMBOLP (elt))
910 temps [argnum++] = Qnil;
911 else if (! NILP (Fcdr (Fcdr (elt))))
912 signal_error ("`let' bindings can have only one value-form", elt);
913 else
914 temps [argnum++] = eval_sub (Fcar (Fcdr (elt)));
915 }
916
917 lexenv = Vinternal_interpreter_environment;
918
919 varlist = XCAR (args);
920 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
921 {
922 Lisp_Object var;
923
924 elt = XCAR (varlist);
925 var = SYMBOLP (elt) ? elt : Fcar (elt);
926 tem = temps[argnum++];
927
928 if (!NILP (lexenv) && SYMBOLP (var)
929 && !XSYMBOL (var)->declared_special
930 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
931 /* Lexically bind VAR by adding it to the lexenv alist. */
932 lexenv = Fcons (Fcons (var, tem), lexenv);
933 else
934 /* Dynamically bind VAR. */
935 specbind (var, tem);
936 }
937
938 if (!EQ (lexenv, Vinternal_interpreter_environment))
939 /* Instantiate a new lexical environment. */
940 specbind (Qinternal_interpreter_environment, lexenv);
941
942 elt = Fprogn (XCDR (args));
943 SAFE_FREE ();
944 return unbind_to (count, elt);
945 }
946
947 DEFUN ("while", Fwhile, Swhile, 1, UNEVALLED, 0,
948 doc: /* If TEST yields non-nil, eval BODY... and repeat.
949 The order of execution is thus TEST, BODY, TEST, BODY and so on
950 until TEST returns nil.
951 usage: (while TEST BODY...) */)
952 (Lisp_Object args)
953 {
954 Lisp_Object test, body;
955
956 test = XCAR (args);
957 body = XCDR (args);
958 while (!NILP (eval_sub (test)))
959 {
960 QUIT;
961 Fprogn (body);
962 }
963
964 return Qnil;
965 }
966
967 DEFUN ("macroexpand", Fmacroexpand, Smacroexpand, 1, 2, 0,
968 doc: /* Return result of expanding macros at top level of FORM.
969 If FORM is not a macro call, it is returned unchanged.
970 Otherwise, the macro is expanded and the expansion is considered
971 in place of FORM. When a non-macro-call results, it is returned.
972
973 The second optional arg ENVIRONMENT specifies an environment of macro
974 definitions to shadow the loaded ones for use in file byte-compilation. */)
975 (Lisp_Object form, Lisp_Object environment)
976 {
977 /* With cleanups from Hallvard Furuseth. */
978 register Lisp_Object expander, sym, def, tem;
979
980 while (1)
981 {
982 /* Come back here each time we expand a macro call,
983 in case it expands into another macro call. */
984 if (!CONSP (form))
985 break;
986 /* Set SYM, give DEF and TEM right values in case SYM is not a symbol. */
987 def = sym = XCAR (form);
988 tem = Qnil;
989 /* Trace symbols aliases to other symbols
990 until we get a symbol that is not an alias. */
991 while (SYMBOLP (def))
992 {
993 QUIT;
994 sym = def;
995 tem = Fassq (sym, environment);
996 if (NILP (tem))
997 {
998 def = XSYMBOL (sym)->function;
999 if (!NILP (def))
1000 continue;
1001 }
1002 break;
1003 }
1004 /* Right now TEM is the result from SYM in ENVIRONMENT,
1005 and if TEM is nil then DEF is SYM's function definition. */
1006 if (NILP (tem))
1007 {
1008 /* SYM is not mentioned in ENVIRONMENT.
1009 Look at its function definition. */
1010 def = Fautoload_do_load (def, sym, Qmacro);
1011 if (!CONSP (def))
1012 /* Not defined or definition not suitable. */
1013 break;
1014 if (!EQ (XCAR (def), Qmacro))
1015 break;
1016 else expander = XCDR (def);
1017 }
1018 else
1019 {
1020 expander = XCDR (tem);
1021 if (NILP (expander))
1022 break;
1023 }
1024 {
1025 Lisp_Object newform = apply1 (expander, XCDR (form));
1026 if (EQ (form, newform))
1027 break;
1028 else
1029 form = newform;
1030 }
1031 }
1032 return form;
1033 }
1034 \f
1035 DEFUN ("catch", Fcatch, Scatch, 1, UNEVALLED, 0,
1036 doc: /* Eval BODY allowing nonlocal exits using `throw'.
1037 TAG is evalled to get the tag to use; it must not be nil.
1038
1039 Then the BODY is executed.
1040 Within BODY, a call to `throw' with the same TAG exits BODY and this `catch'.
1041 If no throw happens, `catch' returns the value of the last BODY form.
1042 If a throw happens, it specifies the value to return from `catch'.
1043 usage: (catch TAG BODY...) */)
1044 (Lisp_Object args)
1045 {
1046 Lisp_Object tag = eval_sub (XCAR (args));
1047 return internal_catch (tag, Fprogn, XCDR (args));
1048 }
1049
1050 /* Assert that E is true, as a comment only. Use this instead of
1051 eassert (E) when E contains variables that might be clobbered by a
1052 longjmp. */
1053
1054 #define clobbered_eassert(E) ((void) 0)
1055
1056 /* Set up a catch, then call C function FUNC on argument ARG.
1057 FUNC should return a Lisp_Object.
1058 This is how catches are done from within C code. */
1059
1060 Lisp_Object
1061 internal_catch (Lisp_Object tag,
1062 Lisp_Object (*func) (Lisp_Object), Lisp_Object arg)
1063 {
1064 /* This structure is made part of the chain `catchlist'. */
1065 struct handler *c = push_handler (tag, CATCHER);
1066
1067 /* Call FUNC. */
1068 if (! sys_setjmp (c->jmp))
1069 {
1070 Lisp_Object val = func (arg);
1071 clobbered_eassert (handlerlist == c);
1072 handlerlist = handlerlist->next;
1073 return val;
1074 }
1075 else
1076 { /* Throw works by a longjmp that comes right here. */
1077 Lisp_Object val = handlerlist->val;
1078 clobbered_eassert (handlerlist == c);
1079 handlerlist = handlerlist->next;
1080 return val;
1081 }
1082 }
1083
1084 /* Unwind the specbind, catch, and handler stacks back to CATCH, and
1085 jump to that CATCH, returning VALUE as the value of that catch.
1086
1087 This is the guts of Fthrow and Fsignal; they differ only in the way
1088 they choose the catch tag to throw to. A catch tag for a
1089 condition-case form has a TAG of Qnil.
1090
1091 Before each catch is discarded, unbind all special bindings and
1092 execute all unwind-protect clauses made above that catch. Unwind
1093 the handler stack as we go, so that the proper handlers are in
1094 effect for each unwind-protect clause we run. At the end, restore
1095 some static info saved in CATCH, and longjmp to the location
1096 specified there.
1097
1098 This is used for correct unwinding in Fthrow and Fsignal. */
1099
1100 static _Noreturn void
1101 unwind_to_catch (struct handler *catch, Lisp_Object value)
1102 {
1103 bool last_time;
1104
1105 eassert (catch->next);
1106
1107 /* Save the value in the tag. */
1108 catch->val = value;
1109
1110 /* Restore certain special C variables. */
1111 set_poll_suppress_count (catch->poll_suppress_count);
1112 unblock_input_to (catch->interrupt_input_blocked);
1113 immediate_quit = 0;
1114
1115 do
1116 {
1117 /* Unwind the specpdl stack, and then restore the proper set of
1118 handlers. */
1119 unbind_to (handlerlist->pdlcount, Qnil);
1120 last_time = handlerlist == catch;
1121 if (! last_time)
1122 handlerlist = handlerlist->next;
1123 }
1124 while (! last_time);
1125
1126 eassert (handlerlist == catch);
1127
1128 byte_stack_list = catch->byte_stack;
1129 lisp_eval_depth = catch->lisp_eval_depth;
1130
1131 sys_longjmp (catch->jmp, 1);
1132 }
1133
1134 DEFUN ("throw", Fthrow, Sthrow, 2, 2, 0,
1135 doc: /* Throw to the catch for TAG and return VALUE from it.
1136 Both TAG and VALUE are evalled. */
1137 attributes: noreturn)
1138 (register Lisp_Object tag, Lisp_Object value)
1139 {
1140 struct handler *c;
1141
1142 if (!NILP (tag))
1143 for (c = handlerlist; c; c = c->next)
1144 {
1145 if (c->type == CATCHER_ALL)
1146 unwind_to_catch (c, Fcons (tag, value));
1147 if (c->type == CATCHER && EQ (c->tag_or_ch, tag))
1148 unwind_to_catch (c, value);
1149 }
1150 xsignal2 (Qno_catch, tag, value);
1151 }
1152
1153
1154 DEFUN ("unwind-protect", Funwind_protect, Sunwind_protect, 1, UNEVALLED, 0,
1155 doc: /* Do BODYFORM, protecting with UNWINDFORMS.
1156 If BODYFORM completes normally, its value is returned
1157 after executing the UNWINDFORMS.
1158 If BODYFORM exits nonlocally, the UNWINDFORMS are executed anyway.
1159 usage: (unwind-protect BODYFORM UNWINDFORMS...) */)
1160 (Lisp_Object args)
1161 {
1162 Lisp_Object val;
1163 ptrdiff_t count = SPECPDL_INDEX ();
1164
1165 record_unwind_protect (unwind_body, XCDR (args));
1166 val = eval_sub (XCAR (args));
1167 return unbind_to (count, val);
1168 }
1169 \f
1170 DEFUN ("condition-case", Fcondition_case, Scondition_case, 2, UNEVALLED, 0,
1171 doc: /* Regain control when an error is signaled.
1172 Executes BODYFORM and returns its value if no error happens.
1173 Each element of HANDLERS looks like (CONDITION-NAME BODY...)
1174 where the BODY is made of Lisp expressions.
1175
1176 A handler is applicable to an error
1177 if CONDITION-NAME is one of the error's condition names.
1178 If an error happens, the first applicable handler is run.
1179
1180 The car of a handler may be a list of condition names instead of a
1181 single condition name; then it handles all of them. If the special
1182 condition name `debug' is present in this list, it allows another
1183 condition in the list to run the debugger if `debug-on-error' and the
1184 other usual mechanisms says it should (otherwise, `condition-case'
1185 suppresses the debugger).
1186
1187 When a handler handles an error, control returns to the `condition-case'
1188 and it executes the handler's BODY...
1189 with VAR bound to (ERROR-SYMBOL . SIGNAL-DATA) from the error.
1190 (If VAR is nil, the handler can't access that information.)
1191 Then the value of the last BODY form is returned from the `condition-case'
1192 expression.
1193
1194 See also the function `signal' for more info.
1195 usage: (condition-case VAR BODYFORM &rest HANDLERS) */)
1196 (Lisp_Object args)
1197 {
1198 Lisp_Object var = XCAR (args);
1199 Lisp_Object bodyform = XCAR (XCDR (args));
1200 Lisp_Object handlers = XCDR (XCDR (args));
1201
1202 return internal_lisp_condition_case (var, bodyform, handlers);
1203 }
1204
1205 /* Like Fcondition_case, but the args are separate
1206 rather than passed in a list. Used by Fbyte_code. */
1207
1208 Lisp_Object
1209 internal_lisp_condition_case (volatile Lisp_Object var, Lisp_Object bodyform,
1210 Lisp_Object handlers)
1211 {
1212 Lisp_Object val;
1213 struct handler *oldhandlerlist = handlerlist;
1214 int clausenb = 0;
1215
1216 CHECK_SYMBOL (var);
1217
1218 for (val = handlers; CONSP (val); val = XCDR (val))
1219 {
1220 Lisp_Object tem = XCAR (val);
1221 clausenb++;
1222 if (! (NILP (tem)
1223 || (CONSP (tem)
1224 && (SYMBOLP (XCAR (tem))
1225 || CONSP (XCAR (tem))))))
1226 error ("Invalid condition handler: %s",
1227 SDATA (Fprin1_to_string (tem, Qt)));
1228 }
1229
1230 { /* The first clause is the one that should be checked first, so it should
1231 be added to handlerlist last. So we build in `clauses' a table that
1232 contains `handlers' but in reverse order. SAFE_ALLOCA won't work
1233 here due to the setjmp, so impose a MAX_ALLOCA limit. */
1234 if (MAX_ALLOCA / word_size < clausenb)
1235 memory_full (SIZE_MAX);
1236 Lisp_Object *clauses = alloca (clausenb * sizeof *clauses);
1237 Lisp_Object *volatile clauses_volatile = clauses;
1238 int i = clausenb;
1239 for (val = handlers; CONSP (val); val = XCDR (val))
1240 clauses[--i] = XCAR (val);
1241 for (i = 0; i < clausenb; i++)
1242 {
1243 Lisp_Object clause = clauses[i];
1244 Lisp_Object condition = XCAR (clause);
1245 if (!CONSP (condition))
1246 condition = Fcons (condition, Qnil);
1247 struct handler *c = push_handler (condition, CONDITION_CASE);
1248 if (sys_setjmp (c->jmp))
1249 {
1250 ptrdiff_t count = SPECPDL_INDEX ();
1251 Lisp_Object val = handlerlist->val;
1252 Lisp_Object *chosen_clause = clauses_volatile;
1253 for (c = handlerlist->next; c != oldhandlerlist; c = c->next)
1254 chosen_clause++;
1255 handlerlist = oldhandlerlist;
1256 if (!NILP (var))
1257 {
1258 if (!NILP (Vinternal_interpreter_environment))
1259 specbind (Qinternal_interpreter_environment,
1260 Fcons (Fcons (var, val),
1261 Vinternal_interpreter_environment));
1262 else
1263 specbind (var, val);
1264 }
1265 val = Fprogn (XCDR (*chosen_clause));
1266 /* Note that this just undoes the binding of var; whoever
1267 longjumped to us unwound the stack to c.pdlcount before
1268 throwing. */
1269 if (!NILP (var))
1270 unbind_to (count, Qnil);
1271 return val;
1272 }
1273 }
1274 }
1275
1276 val = eval_sub (bodyform);
1277 handlerlist = oldhandlerlist;
1278 return val;
1279 }
1280
1281 /* Call the function BFUN with no arguments, catching errors within it
1282 according to HANDLERS. If there is an error, call HFUN with
1283 one argument which is the data that describes the error:
1284 (SIGNALNAME . DATA)
1285
1286 HANDLERS can be a list of conditions to catch.
1287 If HANDLERS is Qt, catch all errors.
1288 If HANDLERS is Qerror, catch all errors
1289 but allow the debugger to run if that is enabled. */
1290
1291 Lisp_Object
1292 internal_condition_case (Lisp_Object (*bfun) (void), Lisp_Object handlers,
1293 Lisp_Object (*hfun) (Lisp_Object))
1294 {
1295 struct handler *c = push_handler (handlers, CONDITION_CASE);
1296 if (sys_setjmp (c->jmp))
1297 {
1298 Lisp_Object val = handlerlist->val;
1299 clobbered_eassert (handlerlist == c);
1300 handlerlist = handlerlist->next;
1301 return hfun (val);
1302 }
1303 else
1304 {
1305 Lisp_Object val = bfun ();
1306 clobbered_eassert (handlerlist == c);
1307 handlerlist = handlerlist->next;
1308 return val;
1309 }
1310 }
1311
1312 /* Like internal_condition_case but call BFUN with ARG as its argument. */
1313
1314 Lisp_Object
1315 internal_condition_case_1 (Lisp_Object (*bfun) (Lisp_Object), Lisp_Object arg,
1316 Lisp_Object handlers,
1317 Lisp_Object (*hfun) (Lisp_Object))
1318 {
1319 struct handler *c = push_handler (handlers, CONDITION_CASE);
1320 if (sys_setjmp (c->jmp))
1321 {
1322 Lisp_Object val = handlerlist->val;
1323 clobbered_eassert (handlerlist == c);
1324 handlerlist = handlerlist->next;
1325 return hfun (val);
1326 }
1327 else
1328 {
1329 Lisp_Object val = bfun (arg);
1330 clobbered_eassert (handlerlist == c);
1331 handlerlist = handlerlist->next;
1332 return val;
1333 }
1334 }
1335
1336 /* Like internal_condition_case_1 but call BFUN with ARG1 and ARG2 as
1337 its arguments. */
1338
1339 Lisp_Object
1340 internal_condition_case_2 (Lisp_Object (*bfun) (Lisp_Object, Lisp_Object),
1341 Lisp_Object arg1,
1342 Lisp_Object arg2,
1343 Lisp_Object handlers,
1344 Lisp_Object (*hfun) (Lisp_Object))
1345 {
1346 struct handler *c = push_handler (handlers, CONDITION_CASE);
1347 if (sys_setjmp (c->jmp))
1348 {
1349 Lisp_Object val = handlerlist->val;
1350 clobbered_eassert (handlerlist == c);
1351 handlerlist = handlerlist->next;
1352 return hfun (val);
1353 }
1354 else
1355 {
1356 Lisp_Object val = bfun (arg1, arg2);
1357 clobbered_eassert (handlerlist == c);
1358 handlerlist = handlerlist->next;
1359 return val;
1360 }
1361 }
1362
1363 /* Like internal_condition_case but call BFUN with NARGS as first,
1364 and ARGS as second argument. */
1365
1366 Lisp_Object
1367 internal_condition_case_n (Lisp_Object (*bfun) (ptrdiff_t, Lisp_Object *),
1368 ptrdiff_t nargs,
1369 Lisp_Object *args,
1370 Lisp_Object handlers,
1371 Lisp_Object (*hfun) (Lisp_Object err,
1372 ptrdiff_t nargs,
1373 Lisp_Object *args))
1374 {
1375 struct handler *c = push_handler (handlers, CONDITION_CASE);
1376 if (sys_setjmp (c->jmp))
1377 {
1378 Lisp_Object val = handlerlist->val;
1379 clobbered_eassert (handlerlist == c);
1380 handlerlist = handlerlist->next;
1381 return hfun (val, nargs, args);
1382 }
1383 else
1384 {
1385 Lisp_Object val = bfun (nargs, args);
1386 clobbered_eassert (handlerlist == c);
1387 handlerlist = handlerlist->next;
1388 return val;
1389 }
1390 }
1391
1392 struct handler *
1393 push_handler (Lisp_Object tag_ch_val, enum handlertype handlertype)
1394 {
1395 struct handler *c = push_handler_nosignal (tag_ch_val, handlertype);
1396 if (!c)
1397 memory_full (sizeof *c);
1398 return c;
1399 }
1400
1401 struct handler *
1402 push_handler_nosignal (Lisp_Object tag_ch_val, enum handlertype handlertype)
1403 {
1404 struct handler *c = handlerlist->nextfree;
1405 if (!c)
1406 {
1407 c = malloc (sizeof *c);
1408 if (!c)
1409 return c;
1410 if (profiler_memory_running)
1411 malloc_probe (sizeof *c);
1412 c->nextfree = NULL;
1413 handlerlist->nextfree = c;
1414 }
1415 c->type = handlertype;
1416 c->tag_or_ch = tag_ch_val;
1417 c->val = Qnil;
1418 c->next = handlerlist;
1419 c->lisp_eval_depth = lisp_eval_depth;
1420 c->pdlcount = SPECPDL_INDEX ();
1421 c->poll_suppress_count = poll_suppress_count;
1422 c->interrupt_input_blocked = interrupt_input_blocked;
1423 c->byte_stack = byte_stack_list;
1424 handlerlist = c;
1425 return c;
1426 }
1427
1428 \f
1429 static Lisp_Object find_handler_clause (Lisp_Object, Lisp_Object);
1430 static bool maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig,
1431 Lisp_Object data);
1432
1433 void
1434 process_quit_flag (void)
1435 {
1436 Lisp_Object flag = Vquit_flag;
1437 Vquit_flag = Qnil;
1438 if (EQ (flag, Qkill_emacs))
1439 Fkill_emacs (Qnil);
1440 if (EQ (Vthrow_on_input, flag))
1441 Fthrow (Vthrow_on_input, Qt);
1442 Fsignal (Qquit, Qnil);
1443 }
1444
1445 DEFUN ("signal", Fsignal, Ssignal, 2, 2, 0,
1446 doc: /* Signal an error. Args are ERROR-SYMBOL and associated DATA.
1447 This function does not return.
1448
1449 An error symbol is a symbol with an `error-conditions' property
1450 that is a list of condition names.
1451 A handler for any of those names will get to handle this signal.
1452 The symbol `error' should normally be one of them.
1453
1454 DATA should be a list. Its elements are printed as part of the error message.
1455 See Info anchor `(elisp)Definition of signal' for some details on how this
1456 error message is constructed.
1457 If the signal is handled, DATA is made available to the handler.
1458 See also the function `condition-case'. */)
1459 (Lisp_Object error_symbol, Lisp_Object data)
1460 {
1461 /* When memory is full, ERROR-SYMBOL is nil,
1462 and DATA is (REAL-ERROR-SYMBOL . REAL-DATA).
1463 That is a special case--don't do this in other situations. */
1464 Lisp_Object conditions;
1465 Lisp_Object string;
1466 Lisp_Object real_error_symbol
1467 = (NILP (error_symbol) ? Fcar (data) : error_symbol);
1468 register Lisp_Object clause = Qnil;
1469 struct handler *h;
1470
1471 immediate_quit = 0;
1472 abort_on_gc = 0;
1473 if (gc_in_progress || waiting_for_input)
1474 emacs_abort ();
1475
1476 #if 0 /* rms: I don't know why this was here,
1477 but it is surely wrong for an error that is handled. */
1478 #ifdef HAVE_WINDOW_SYSTEM
1479 if (display_hourglass_p)
1480 cancel_hourglass ();
1481 #endif
1482 #endif
1483
1484 /* This hook is used by edebug. */
1485 if (! NILP (Vsignal_hook_function)
1486 && ! NILP (error_symbol))
1487 {
1488 /* Edebug takes care of restoring these variables when it exits. */
1489 if (lisp_eval_depth + 20 > max_lisp_eval_depth)
1490 max_lisp_eval_depth = lisp_eval_depth + 20;
1491
1492 if (SPECPDL_INDEX () + 40 > max_specpdl_size)
1493 max_specpdl_size = SPECPDL_INDEX () + 40;
1494
1495 call2 (Vsignal_hook_function, error_symbol, data);
1496 }
1497
1498 conditions = Fget (real_error_symbol, Qerror_conditions);
1499
1500 /* Remember from where signal was called. Skip over the frame for
1501 `signal' itself. If a frame for `error' follows, skip that,
1502 too. Don't do this when ERROR_SYMBOL is nil, because that
1503 is a memory-full error. */
1504 Vsignaling_function = Qnil;
1505 if (!NILP (error_symbol))
1506 {
1507 union specbinding *pdl = backtrace_next (backtrace_top ());
1508 if (backtrace_p (pdl) && EQ (backtrace_function (pdl), Qerror))
1509 pdl = backtrace_next (pdl);
1510 if (backtrace_p (pdl))
1511 Vsignaling_function = backtrace_function (pdl);
1512 }
1513
1514 for (h = handlerlist; h; h = h->next)
1515 {
1516 if (h->type != CONDITION_CASE)
1517 continue;
1518 clause = find_handler_clause (h->tag_or_ch, conditions);
1519 if (!NILP (clause))
1520 break;
1521 }
1522
1523 if (/* Don't run the debugger for a memory-full error.
1524 (There is no room in memory to do that!) */
1525 !NILP (error_symbol)
1526 && (!NILP (Vdebug_on_signal)
1527 /* If no handler is present now, try to run the debugger. */
1528 || NILP (clause)
1529 /* A `debug' symbol in the handler list disables the normal
1530 suppression of the debugger. */
1531 || (CONSP (clause) && !NILP (Fmemq (Qdebug, clause)))
1532 /* Special handler that means "print a message and run debugger
1533 if requested". */
1534 || EQ (h->tag_or_ch, Qerror)))
1535 {
1536 bool debugger_called
1537 = maybe_call_debugger (conditions, error_symbol, data);
1538 /* We can't return values to code which signaled an error, but we
1539 can continue code which has signaled a quit. */
1540 if (debugger_called && EQ (real_error_symbol, Qquit))
1541 return Qnil;
1542 }
1543
1544 if (!NILP (clause))
1545 {
1546 Lisp_Object unwind_data
1547 = (NILP (error_symbol) ? data : Fcons (error_symbol, data));
1548
1549 unwind_to_catch (h, unwind_data);
1550 }
1551 else
1552 {
1553 if (handlerlist != &handlerlist_sentinel)
1554 /* FIXME: This will come right back here if there's no `top-level'
1555 catcher. A better solution would be to abort here, and instead
1556 add a catch-all condition handler so we never come here. */
1557 Fthrow (Qtop_level, Qt);
1558 }
1559
1560 if (! NILP (error_symbol))
1561 data = Fcons (error_symbol, data);
1562
1563 string = Ferror_message_string (data);
1564 fatal ("%s", SDATA (string));
1565 }
1566
1567 /* Internal version of Fsignal that never returns.
1568 Used for anything but Qquit (which can return from Fsignal). */
1569
1570 void
1571 xsignal (Lisp_Object error_symbol, Lisp_Object data)
1572 {
1573 Fsignal (error_symbol, data);
1574 emacs_abort ();
1575 }
1576
1577 /* Like xsignal, but takes 0, 1, 2, or 3 args instead of a list. */
1578
1579 void
1580 xsignal0 (Lisp_Object error_symbol)
1581 {
1582 xsignal (error_symbol, Qnil);
1583 }
1584
1585 void
1586 xsignal1 (Lisp_Object error_symbol, Lisp_Object arg)
1587 {
1588 xsignal (error_symbol, list1 (arg));
1589 }
1590
1591 void
1592 xsignal2 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2)
1593 {
1594 xsignal (error_symbol, list2 (arg1, arg2));
1595 }
1596
1597 void
1598 xsignal3 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
1599 {
1600 xsignal (error_symbol, list3 (arg1, arg2, arg3));
1601 }
1602
1603 /* Signal `error' with message S, and additional arg ARG.
1604 If ARG is not a genuine list, make it a one-element list. */
1605
1606 void
1607 signal_error (const char *s, Lisp_Object arg)
1608 {
1609 Lisp_Object tortoise, hare;
1610
1611 hare = tortoise = arg;
1612 while (CONSP (hare))
1613 {
1614 hare = XCDR (hare);
1615 if (!CONSP (hare))
1616 break;
1617
1618 hare = XCDR (hare);
1619 tortoise = XCDR (tortoise);
1620
1621 if (EQ (hare, tortoise))
1622 break;
1623 }
1624
1625 if (!NILP (hare))
1626 arg = list1 (arg);
1627
1628 xsignal (Qerror, Fcons (build_string (s), arg));
1629 }
1630
1631
1632 /* Return true if LIST is a non-nil atom or
1633 a list containing one of CONDITIONS. */
1634
1635 static bool
1636 wants_debugger (Lisp_Object list, Lisp_Object conditions)
1637 {
1638 if (NILP (list))
1639 return 0;
1640 if (! CONSP (list))
1641 return 1;
1642
1643 while (CONSP (conditions))
1644 {
1645 Lisp_Object this, tail;
1646 this = XCAR (conditions);
1647 for (tail = list; CONSP (tail); tail = XCDR (tail))
1648 if (EQ (XCAR (tail), this))
1649 return 1;
1650 conditions = XCDR (conditions);
1651 }
1652 return 0;
1653 }
1654
1655 /* Return true if an error with condition-symbols CONDITIONS,
1656 and described by SIGNAL-DATA, should skip the debugger
1657 according to debugger-ignored-errors. */
1658
1659 static bool
1660 skip_debugger (Lisp_Object conditions, Lisp_Object data)
1661 {
1662 Lisp_Object tail;
1663 bool first_string = 1;
1664 Lisp_Object error_message;
1665
1666 error_message = Qnil;
1667 for (tail = Vdebug_ignored_errors; CONSP (tail); tail = XCDR (tail))
1668 {
1669 if (STRINGP (XCAR (tail)))
1670 {
1671 if (first_string)
1672 {
1673 error_message = Ferror_message_string (data);
1674 first_string = 0;
1675 }
1676
1677 if (fast_string_match (XCAR (tail), error_message) >= 0)
1678 return 1;
1679 }
1680 else
1681 {
1682 Lisp_Object contail;
1683
1684 for (contail = conditions; CONSP (contail); contail = XCDR (contail))
1685 if (EQ (XCAR (tail), XCAR (contail)))
1686 return 1;
1687 }
1688 }
1689
1690 return 0;
1691 }
1692
1693 /* Call the debugger if calling it is currently enabled for CONDITIONS.
1694 SIG and DATA describe the signal. There are two ways to pass them:
1695 = SIG is the error symbol, and DATA is the rest of the data.
1696 = SIG is nil, and DATA is (SYMBOL . REST-OF-DATA).
1697 This is for memory-full errors only. */
1698 static bool
1699 maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig, Lisp_Object data)
1700 {
1701 Lisp_Object combined_data;
1702
1703 combined_data = Fcons (sig, data);
1704
1705 if (
1706 /* Don't try to run the debugger with interrupts blocked.
1707 The editing loop would return anyway. */
1708 ! input_blocked_p ()
1709 && NILP (Vinhibit_debugger)
1710 /* Does user want to enter debugger for this kind of error? */
1711 && (EQ (sig, Qquit)
1712 ? debug_on_quit
1713 : wants_debugger (Vdebug_on_error, conditions))
1714 && ! skip_debugger (conditions, combined_data)
1715 /* RMS: What's this for? */
1716 && when_entered_debugger < num_nonmacro_input_events)
1717 {
1718 call_debugger (list2 (Qerror, combined_data));
1719 return 1;
1720 }
1721
1722 return 0;
1723 }
1724
1725 static Lisp_Object
1726 find_handler_clause (Lisp_Object handlers, Lisp_Object conditions)
1727 {
1728 register Lisp_Object h;
1729
1730 /* t is used by handlers for all conditions, set up by C code. */
1731 if (EQ (handlers, Qt))
1732 return Qt;
1733
1734 /* error is used similarly, but means print an error message
1735 and run the debugger if that is enabled. */
1736 if (EQ (handlers, Qerror))
1737 return Qt;
1738
1739 for (h = handlers; CONSP (h); h = XCDR (h))
1740 {
1741 Lisp_Object handler = XCAR (h);
1742 if (!NILP (Fmemq (handler, conditions)))
1743 return handlers;
1744 }
1745
1746 return Qnil;
1747 }
1748
1749
1750 /* Dump an error message; called like vprintf. */
1751 void
1752 verror (const char *m, va_list ap)
1753 {
1754 char buf[4000];
1755 ptrdiff_t size = sizeof buf;
1756 ptrdiff_t size_max = STRING_BYTES_BOUND + 1;
1757 char *buffer = buf;
1758 ptrdiff_t used;
1759 Lisp_Object string;
1760
1761 used = evxprintf (&buffer, &size, buf, size_max, m, ap);
1762 string = make_string (buffer, used);
1763 if (buffer != buf)
1764 xfree (buffer);
1765
1766 xsignal1 (Qerror, string);
1767 }
1768
1769
1770 /* Dump an error message; called like printf. */
1771
1772 /* VARARGS 1 */
1773 void
1774 error (const char *m, ...)
1775 {
1776 va_list ap;
1777 va_start (ap, m);
1778 verror (m, ap);
1779 }
1780 \f
1781 DEFUN ("commandp", Fcommandp, Scommandp, 1, 2, 0,
1782 doc: /* Non-nil if FUNCTION makes provisions for interactive calling.
1783 This means it contains a description for how to read arguments to give it.
1784 The value is nil for an invalid function or a symbol with no function
1785 definition.
1786
1787 Interactively callable functions include strings and vectors (treated
1788 as keyboard macros), lambda-expressions that contain a top-level call
1789 to `interactive', autoload definitions made by `autoload' with non-nil
1790 fourth argument, and some of the built-in functions of Lisp.
1791
1792 Also, a symbol satisfies `commandp' if its function definition does so.
1793
1794 If the optional argument FOR-CALL-INTERACTIVELY is non-nil,
1795 then strings and vectors are not accepted. */)
1796 (Lisp_Object function, Lisp_Object for_call_interactively)
1797 {
1798 register Lisp_Object fun;
1799 register Lisp_Object funcar;
1800 Lisp_Object if_prop = Qnil;
1801
1802 fun = function;
1803
1804 fun = indirect_function (fun); /* Check cycles. */
1805 if (NILP (fun))
1806 return Qnil;
1807
1808 /* Check an `interactive-form' property if present, analogous to the
1809 function-documentation property. */
1810 fun = function;
1811 while (SYMBOLP (fun))
1812 {
1813 Lisp_Object tmp = Fget (fun, Qinteractive_form);
1814 if (!NILP (tmp))
1815 if_prop = Qt;
1816 fun = Fsymbol_function (fun);
1817 }
1818
1819 /* Emacs primitives are interactive if their DEFUN specifies an
1820 interactive spec. */
1821 if (SUBRP (fun))
1822 return XSUBR (fun)->intspec ? Qt : if_prop;
1823
1824 /* Bytecode objects are interactive if they are long enough to
1825 have an element whose index is COMPILED_INTERACTIVE, which is
1826 where the interactive spec is stored. */
1827 else if (COMPILEDP (fun))
1828 return ((ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK) > COMPILED_INTERACTIVE
1829 ? Qt : if_prop);
1830
1831 /* Strings and vectors are keyboard macros. */
1832 if (STRINGP (fun) || VECTORP (fun))
1833 return (NILP (for_call_interactively) ? Qt : Qnil);
1834
1835 /* Lists may represent commands. */
1836 if (!CONSP (fun))
1837 return Qnil;
1838 funcar = XCAR (fun);
1839 if (EQ (funcar, Qclosure))
1840 return (!NILP (Fassq (Qinteractive, Fcdr (Fcdr (XCDR (fun)))))
1841 ? Qt : if_prop);
1842 else if (EQ (funcar, Qlambda))
1843 return !NILP (Fassq (Qinteractive, Fcdr (XCDR (fun)))) ? Qt : if_prop;
1844 else if (EQ (funcar, Qautoload))
1845 return !NILP (Fcar (Fcdr (Fcdr (XCDR (fun))))) ? Qt : if_prop;
1846 else
1847 return Qnil;
1848 }
1849
1850 DEFUN ("autoload", Fautoload, Sautoload, 2, 5, 0,
1851 doc: /* Define FUNCTION to autoload from FILE.
1852 FUNCTION is a symbol; FILE is a file name string to pass to `load'.
1853 Third arg DOCSTRING is documentation for the function.
1854 Fourth arg INTERACTIVE if non-nil says function can be called interactively.
1855 Fifth arg TYPE indicates the type of the object:
1856 nil or omitted says FUNCTION is a function,
1857 `keymap' says FUNCTION is really a keymap, and
1858 `macro' or t says FUNCTION is really a macro.
1859 Third through fifth args give info about the real definition.
1860 They default to nil.
1861 If FUNCTION is already defined other than as an autoload,
1862 this does nothing and returns nil. */)
1863 (Lisp_Object function, Lisp_Object file, Lisp_Object docstring, Lisp_Object interactive, Lisp_Object type)
1864 {
1865 CHECK_SYMBOL (function);
1866 CHECK_STRING (file);
1867
1868 /* If function is defined and not as an autoload, don't override. */
1869 if (!NILP (XSYMBOL (function)->function)
1870 && !AUTOLOADP (XSYMBOL (function)->function))
1871 return Qnil;
1872
1873 if (!NILP (Vpurify_flag) && EQ (docstring, make_number (0)))
1874 /* `read1' in lread.c has found the docstring starting with "\
1875 and assumed the docstring will be provided by Snarf-documentation, so it
1876 passed us 0 instead. But that leads to accidental sharing in purecopy's
1877 hash-consing, so we use a (hopefully) unique integer instead. */
1878 docstring = make_number (XHASH (function));
1879 return Fdefalias (function,
1880 list5 (Qautoload, file, docstring, interactive, type),
1881 Qnil);
1882 }
1883
1884 void
1885 un_autoload (Lisp_Object oldqueue)
1886 {
1887 Lisp_Object queue, first, second;
1888
1889 /* Queue to unwind is current value of Vautoload_queue.
1890 oldqueue is the shadowed value to leave in Vautoload_queue. */
1891 queue = Vautoload_queue;
1892 Vautoload_queue = oldqueue;
1893 while (CONSP (queue))
1894 {
1895 first = XCAR (queue);
1896 second = Fcdr (first);
1897 first = Fcar (first);
1898 if (EQ (first, make_number (0)))
1899 Vfeatures = second;
1900 else
1901 Ffset (first, second);
1902 queue = XCDR (queue);
1903 }
1904 }
1905
1906 /* Load an autoloaded function.
1907 FUNNAME is the symbol which is the function's name.
1908 FUNDEF is the autoload definition (a list). */
1909
1910 DEFUN ("autoload-do-load", Fautoload_do_load, Sautoload_do_load, 1, 3, 0,
1911 doc: /* Load FUNDEF which should be an autoload.
1912 If non-nil, FUNNAME should be the symbol whose function value is FUNDEF,
1913 in which case the function returns the new autoloaded function value.
1914 If equal to `macro', MACRO-ONLY specifies that FUNDEF should only be loaded if
1915 it defines a macro. */)
1916 (Lisp_Object fundef, Lisp_Object funname, Lisp_Object macro_only)
1917 {
1918 ptrdiff_t count = SPECPDL_INDEX ();
1919
1920 if (!CONSP (fundef) || !EQ (Qautoload, XCAR (fundef)))
1921 return fundef;
1922
1923 if (EQ (macro_only, Qmacro))
1924 {
1925 Lisp_Object kind = Fnth (make_number (4), fundef);
1926 if (! (EQ (kind, Qt) || EQ (kind, Qmacro)))
1927 return fundef;
1928 }
1929
1930 /* This is to make sure that loadup.el gives a clear picture
1931 of what files are preloaded and when. */
1932 if (! NILP (Vpurify_flag))
1933 error ("Attempt to autoload %s while preparing to dump",
1934 SDATA (SYMBOL_NAME (funname)));
1935
1936 CHECK_SYMBOL (funname);
1937
1938 /* Preserve the match data. */
1939 record_unwind_save_match_data ();
1940
1941 /* If autoloading gets an error (which includes the error of failing
1942 to define the function being called), we use Vautoload_queue
1943 to undo function definitions and `provide' calls made by
1944 the function. We do this in the specific case of autoloading
1945 because autoloading is not an explicit request "load this file",
1946 but rather a request to "call this function".
1947
1948 The value saved here is to be restored into Vautoload_queue. */
1949 record_unwind_protect (un_autoload, Vautoload_queue);
1950 Vautoload_queue = Qt;
1951 /* If `macro_only', assume this autoload to be a "best-effort",
1952 so don't signal an error if autoloading fails. */
1953 Fload (Fcar (Fcdr (fundef)), macro_only, Qt, Qnil, Qt);
1954
1955 /* Once loading finishes, don't undo it. */
1956 Vautoload_queue = Qt;
1957 unbind_to (count, Qnil);
1958
1959 if (NILP (funname))
1960 return Qnil;
1961 else
1962 {
1963 Lisp_Object fun = Findirect_function (funname, Qnil);
1964
1965 if (!NILP (Fequal (fun, fundef)))
1966 error ("Autoloading failed to define function %s",
1967 SDATA (SYMBOL_NAME (funname)));
1968 else
1969 return fun;
1970 }
1971 }
1972
1973 \f
1974 DEFUN ("eval", Feval, Seval, 1, 2, 0,
1975 doc: /* Evaluate FORM and return its value.
1976 If LEXICAL is t, evaluate using lexical scoping.
1977 LEXICAL can also be an actual lexical environment, in the form of an
1978 alist mapping symbols to their value. */)
1979 (Lisp_Object form, Lisp_Object lexical)
1980 {
1981 ptrdiff_t count = SPECPDL_INDEX ();
1982 specbind (Qinternal_interpreter_environment,
1983 CONSP (lexical) || NILP (lexical) ? lexical : list1 (Qt));
1984 return unbind_to (count, eval_sub (form));
1985 }
1986
1987 /* Grow the specpdl stack by one entry.
1988 The caller should have already initialized the entry.
1989 Signal an error on stack overflow.
1990
1991 Make sure that there is always one unused entry past the top of the
1992 stack, so that the just-initialized entry is safely unwound if
1993 memory exhausted and an error is signaled here. Also, allocate a
1994 never-used entry just before the bottom of the stack; sometimes its
1995 address is taken. */
1996
1997 static void
1998 grow_specpdl (void)
1999 {
2000 specpdl_ptr++;
2001
2002 if (specpdl_ptr == specpdl + specpdl_size)
2003 {
2004 ptrdiff_t count = SPECPDL_INDEX ();
2005 ptrdiff_t max_size = min (max_specpdl_size, PTRDIFF_MAX - 1000);
2006 union specbinding *pdlvec = specpdl - 1;
2007 ptrdiff_t pdlvecsize = specpdl_size + 1;
2008 if (max_size <= specpdl_size)
2009 {
2010 if (max_specpdl_size < 400)
2011 max_size = max_specpdl_size = 400;
2012 if (max_size <= specpdl_size)
2013 signal_error ("Variable binding depth exceeds max-specpdl-size",
2014 Qnil);
2015 }
2016 pdlvec = xpalloc (pdlvec, &pdlvecsize, 1, max_size + 1, sizeof *specpdl);
2017 specpdl = pdlvec + 1;
2018 specpdl_size = pdlvecsize - 1;
2019 specpdl_ptr = specpdl + count;
2020 }
2021 }
2022
2023 ptrdiff_t
2024 record_in_backtrace (Lisp_Object function, Lisp_Object *args, ptrdiff_t nargs)
2025 {
2026 ptrdiff_t count = SPECPDL_INDEX ();
2027
2028 eassert (nargs >= UNEVALLED);
2029 specpdl_ptr->bt.kind = SPECPDL_BACKTRACE;
2030 specpdl_ptr->bt.debug_on_exit = false;
2031 specpdl_ptr->bt.function = function;
2032 specpdl_ptr->bt.args = args;
2033 specpdl_ptr->bt.nargs = nargs;
2034 grow_specpdl ();
2035
2036 return count;
2037 }
2038
2039 /* Eval a sub-expression of the current expression (i.e. in the same
2040 lexical scope). */
2041 Lisp_Object
2042 eval_sub (Lisp_Object form)
2043 {
2044 Lisp_Object fun, val, original_fun, original_args;
2045 Lisp_Object funcar;
2046 ptrdiff_t count;
2047
2048 /* Declare here, as this array may be accessed by call_debugger near
2049 the end of this function. See Bug#21245. */
2050 Lisp_Object argvals[8];
2051
2052 if (SYMBOLP (form))
2053 {
2054 /* Look up its binding in the lexical environment.
2055 We do not pay attention to the declared_special flag here, since we
2056 already did that when let-binding the variable. */
2057 Lisp_Object lex_binding
2058 = !NILP (Vinternal_interpreter_environment) /* Mere optimization! */
2059 ? Fassq (form, Vinternal_interpreter_environment)
2060 : Qnil;
2061 if (CONSP (lex_binding))
2062 return XCDR (lex_binding);
2063 else
2064 return Fsymbol_value (form);
2065 }
2066
2067 if (!CONSP (form))
2068 return form;
2069
2070 QUIT;
2071
2072 maybe_gc ();
2073
2074 if (++lisp_eval_depth > max_lisp_eval_depth)
2075 {
2076 if (max_lisp_eval_depth < 100)
2077 max_lisp_eval_depth = 100;
2078 if (lisp_eval_depth > max_lisp_eval_depth)
2079 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2080 }
2081
2082 original_fun = XCAR (form);
2083 original_args = XCDR (form);
2084
2085 /* This also protects them from gc. */
2086 count = record_in_backtrace (original_fun, &original_args, UNEVALLED);
2087
2088 if (debug_on_next_call)
2089 do_debug_on_call (Qt, count);
2090
2091 /* At this point, only original_fun and original_args
2092 have values that will be used below. */
2093 retry:
2094
2095 /* Optimize for no indirection. */
2096 fun = original_fun;
2097 if (!SYMBOLP (fun))
2098 fun = Ffunction (Fcons (fun, Qnil));
2099 else if (!NILP (fun) && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2100 fun = indirect_function (fun);
2101
2102 if (SUBRP (fun))
2103 {
2104 Lisp_Object args_left = original_args;
2105 Lisp_Object numargs = Flength (args_left);
2106
2107 check_cons_list ();
2108
2109 if (XINT (numargs) < XSUBR (fun)->min_args
2110 || (XSUBR (fun)->max_args >= 0
2111 && XSUBR (fun)->max_args < XINT (numargs)))
2112 xsignal2 (Qwrong_number_of_arguments, original_fun, numargs);
2113
2114 else if (XSUBR (fun)->max_args == UNEVALLED)
2115 val = (XSUBR (fun)->function.aUNEVALLED) (args_left);
2116 else if (XSUBR (fun)->max_args == MANY)
2117 {
2118 /* Pass a vector of evaluated arguments. */
2119 Lisp_Object *vals;
2120 ptrdiff_t argnum = 0;
2121 USE_SAFE_ALLOCA;
2122
2123 SAFE_ALLOCA_LISP (vals, XINT (numargs));
2124
2125 while (!NILP (args_left))
2126 {
2127 vals[argnum++] = eval_sub (Fcar (args_left));
2128 args_left = Fcdr (args_left);
2129 }
2130
2131 set_backtrace_args (specpdl + count, vals, XINT (numargs));
2132
2133 val = (XSUBR (fun)->function.aMANY) (XINT (numargs), vals);
2134
2135 check_cons_list ();
2136 lisp_eval_depth--;
2137 /* Do the debug-on-exit now, while VALS still exists. */
2138 if (backtrace_debug_on_exit (specpdl + count))
2139 val = call_debugger (list2 (Qexit, val));
2140 SAFE_FREE ();
2141 specpdl_ptr--;
2142 return val;
2143 }
2144 else
2145 {
2146 int i, maxargs = XSUBR (fun)->max_args;
2147
2148 for (i = 0; i < maxargs; i++)
2149 {
2150 argvals[i] = eval_sub (Fcar (args_left));
2151 args_left = Fcdr (args_left);
2152 }
2153
2154 set_backtrace_args (specpdl + count, argvals, XINT (numargs));
2155
2156 switch (i)
2157 {
2158 case 0:
2159 val = (XSUBR (fun)->function.a0 ());
2160 break;
2161 case 1:
2162 val = (XSUBR (fun)->function.a1 (argvals[0]));
2163 break;
2164 case 2:
2165 val = (XSUBR (fun)->function.a2 (argvals[0], argvals[1]));
2166 break;
2167 case 3:
2168 val = (XSUBR (fun)->function.a3
2169 (argvals[0], argvals[1], argvals[2]));
2170 break;
2171 case 4:
2172 val = (XSUBR (fun)->function.a4
2173 (argvals[0], argvals[1], argvals[2], argvals[3]));
2174 break;
2175 case 5:
2176 val = (XSUBR (fun)->function.a5
2177 (argvals[0], argvals[1], argvals[2], argvals[3],
2178 argvals[4]));
2179 break;
2180 case 6:
2181 val = (XSUBR (fun)->function.a6
2182 (argvals[0], argvals[1], argvals[2], argvals[3],
2183 argvals[4], argvals[5]));
2184 break;
2185 case 7:
2186 val = (XSUBR (fun)->function.a7
2187 (argvals[0], argvals[1], argvals[2], argvals[3],
2188 argvals[4], argvals[5], argvals[6]));
2189 break;
2190
2191 case 8:
2192 val = (XSUBR (fun)->function.a8
2193 (argvals[0], argvals[1], argvals[2], argvals[3],
2194 argvals[4], argvals[5], argvals[6], argvals[7]));
2195 break;
2196
2197 default:
2198 /* Someone has created a subr that takes more arguments than
2199 is supported by this code. We need to either rewrite the
2200 subr to use a different argument protocol, or add more
2201 cases to this switch. */
2202 emacs_abort ();
2203 }
2204 }
2205 }
2206 else if (COMPILEDP (fun))
2207 return apply_lambda (fun, original_args, count);
2208 else
2209 {
2210 if (NILP (fun))
2211 xsignal1 (Qvoid_function, original_fun);
2212 if (!CONSP (fun))
2213 xsignal1 (Qinvalid_function, original_fun);
2214 funcar = XCAR (fun);
2215 if (!SYMBOLP (funcar))
2216 xsignal1 (Qinvalid_function, original_fun);
2217 if (EQ (funcar, Qautoload))
2218 {
2219 Fautoload_do_load (fun, original_fun, Qnil);
2220 goto retry;
2221 }
2222 if (EQ (funcar, Qmacro))
2223 {
2224 ptrdiff_t count1 = SPECPDL_INDEX ();
2225 Lisp_Object exp;
2226 /* Bind lexical-binding during expansion of the macro, so the
2227 macro can know reliably if the code it outputs will be
2228 interpreted using lexical-binding or not. */
2229 specbind (Qlexical_binding,
2230 NILP (Vinternal_interpreter_environment) ? Qnil : Qt);
2231 exp = apply1 (Fcdr (fun), original_args);
2232 unbind_to (count1, Qnil);
2233 val = eval_sub (exp);
2234 }
2235 else if (EQ (funcar, Qlambda)
2236 || EQ (funcar, Qclosure))
2237 return apply_lambda (fun, original_args, count);
2238 else
2239 xsignal1 (Qinvalid_function, original_fun);
2240 }
2241 check_cons_list ();
2242
2243 lisp_eval_depth--;
2244 if (backtrace_debug_on_exit (specpdl + count))
2245 val = call_debugger (list2 (Qexit, val));
2246 specpdl_ptr--;
2247
2248 return val;
2249 }
2250 \f
2251 DEFUN ("apply", Fapply, Sapply, 1, MANY, 0,
2252 doc: /* Call FUNCTION with our remaining args, using our last arg as list of args.
2253 Then return the value FUNCTION returns.
2254 Thus, (apply \\='+ 1 2 \\='(3 4)) returns 10.
2255 usage: (apply FUNCTION &rest ARGUMENTS) */)
2256 (ptrdiff_t nargs, Lisp_Object *args)
2257 {
2258 ptrdiff_t i, numargs, funcall_nargs;
2259 register Lisp_Object *funcall_args = NULL;
2260 register Lisp_Object spread_arg = args[nargs - 1];
2261 Lisp_Object fun = args[0];
2262 Lisp_Object retval;
2263 USE_SAFE_ALLOCA;
2264
2265 CHECK_LIST (spread_arg);
2266
2267 numargs = XINT (Flength (spread_arg));
2268
2269 if (numargs == 0)
2270 return Ffuncall (nargs - 1, args);
2271 else if (numargs == 1)
2272 {
2273 args [nargs - 1] = XCAR (spread_arg);
2274 return Ffuncall (nargs, args);
2275 }
2276
2277 numargs += nargs - 2;
2278
2279 /* Optimize for no indirection. */
2280 if (SYMBOLP (fun) && !NILP (fun)
2281 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2282 {
2283 fun = indirect_function (fun);
2284 if (NILP (fun))
2285 /* Let funcall get the error. */
2286 fun = args[0];
2287 }
2288
2289 if (SUBRP (fun) && XSUBR (fun)->max_args > numargs
2290 /* Don't hide an error by adding missing arguments. */
2291 && numargs >= XSUBR (fun)->min_args)
2292 {
2293 /* Avoid making funcall cons up a yet another new vector of arguments
2294 by explicitly supplying nil's for optional values. */
2295 SAFE_ALLOCA_LISP (funcall_args, 1 + XSUBR (fun)->max_args);
2296 memclear (funcall_args + numargs + 1,
2297 (XSUBR (fun)->max_args - numargs) * word_size);
2298 funcall_nargs = 1 + XSUBR (fun)->max_args;
2299 }
2300 else
2301 { /* We add 1 to numargs because funcall_args includes the
2302 function itself as well as its arguments. */
2303 SAFE_ALLOCA_LISP (funcall_args, 1 + numargs);
2304 funcall_nargs = 1 + numargs;
2305 }
2306
2307 memcpy (funcall_args, args, nargs * word_size);
2308 /* Spread the last arg we got. Its first element goes in
2309 the slot that it used to occupy, hence this value of I. */
2310 i = nargs - 1;
2311 while (!NILP (spread_arg))
2312 {
2313 funcall_args [i++] = XCAR (spread_arg);
2314 spread_arg = XCDR (spread_arg);
2315 }
2316
2317 retval = Ffuncall (funcall_nargs, funcall_args);
2318
2319 SAFE_FREE ();
2320 return retval;
2321 }
2322 \f
2323 /* Run hook variables in various ways. */
2324
2325 static Lisp_Object
2326 funcall_nil (ptrdiff_t nargs, Lisp_Object *args)
2327 {
2328 Ffuncall (nargs, args);
2329 return Qnil;
2330 }
2331
2332 DEFUN ("run-hooks", Frun_hooks, Srun_hooks, 0, MANY, 0,
2333 doc: /* Run each hook in HOOKS.
2334 Each argument should be a symbol, a hook variable.
2335 These symbols are processed in the order specified.
2336 If a hook symbol has a non-nil value, that value may be a function
2337 or a list of functions to be called to run the hook.
2338 If the value is a function, it is called with no arguments.
2339 If it is a list, the elements are called, in order, with no arguments.
2340
2341 Major modes should not use this function directly to run their mode
2342 hook; they should use `run-mode-hooks' instead.
2343
2344 Do not use `make-local-variable' to make a hook variable buffer-local.
2345 Instead, use `add-hook' and specify t for the LOCAL argument.
2346 usage: (run-hooks &rest HOOKS) */)
2347 (ptrdiff_t nargs, Lisp_Object *args)
2348 {
2349 ptrdiff_t i;
2350
2351 for (i = 0; i < nargs; i++)
2352 run_hook (args[i]);
2353
2354 return Qnil;
2355 }
2356
2357 DEFUN ("run-hook-with-args", Frun_hook_with_args,
2358 Srun_hook_with_args, 1, MANY, 0,
2359 doc: /* Run HOOK with the specified arguments ARGS.
2360 HOOK should be a symbol, a hook variable. The value of HOOK
2361 may be nil, a function, or a list of functions. Call each
2362 function in order with arguments ARGS. The final return value
2363 is unspecified.
2364
2365 Do not use `make-local-variable' to make a hook variable buffer-local.
2366 Instead, use `add-hook' and specify t for the LOCAL argument.
2367 usage: (run-hook-with-args HOOK &rest ARGS) */)
2368 (ptrdiff_t nargs, Lisp_Object *args)
2369 {
2370 return run_hook_with_args (nargs, args, funcall_nil);
2371 }
2372
2373 /* NB this one still documents a specific non-nil return value.
2374 (As did run-hook-with-args and run-hook-with-args-until-failure
2375 until they were changed in 24.1.) */
2376 DEFUN ("run-hook-with-args-until-success", Frun_hook_with_args_until_success,
2377 Srun_hook_with_args_until_success, 1, MANY, 0,
2378 doc: /* Run HOOK with the specified arguments ARGS.
2379 HOOK should be a symbol, a hook variable. The value of HOOK
2380 may be nil, a function, or a list of functions. Call each
2381 function in order with arguments ARGS, stopping at the first
2382 one that returns non-nil, and return that value. Otherwise (if
2383 all functions return nil, or if there are no functions to call),
2384 return nil.
2385
2386 Do not use `make-local-variable' to make a hook variable buffer-local.
2387 Instead, use `add-hook' and specify t for the LOCAL argument.
2388 usage: (run-hook-with-args-until-success HOOK &rest ARGS) */)
2389 (ptrdiff_t nargs, Lisp_Object *args)
2390 {
2391 return run_hook_with_args (nargs, args, Ffuncall);
2392 }
2393
2394 static Lisp_Object
2395 funcall_not (ptrdiff_t nargs, Lisp_Object *args)
2396 {
2397 return NILP (Ffuncall (nargs, args)) ? Qt : Qnil;
2398 }
2399
2400 DEFUN ("run-hook-with-args-until-failure", Frun_hook_with_args_until_failure,
2401 Srun_hook_with_args_until_failure, 1, MANY, 0,
2402 doc: /* Run HOOK with the specified arguments ARGS.
2403 HOOK should be a symbol, a hook variable. The value of HOOK
2404 may be nil, a function, or a list of functions. Call each
2405 function in order with arguments ARGS, stopping at the first
2406 one that returns nil, and return nil. Otherwise (if all functions
2407 return non-nil, or if there are no functions to call), return non-nil
2408 (do not rely on the precise return value in this case).
2409
2410 Do not use `make-local-variable' to make a hook variable buffer-local.
2411 Instead, use `add-hook' and specify t for the LOCAL argument.
2412 usage: (run-hook-with-args-until-failure HOOK &rest ARGS) */)
2413 (ptrdiff_t nargs, Lisp_Object *args)
2414 {
2415 return NILP (run_hook_with_args (nargs, args, funcall_not)) ? Qt : Qnil;
2416 }
2417
2418 static Lisp_Object
2419 run_hook_wrapped_funcall (ptrdiff_t nargs, Lisp_Object *args)
2420 {
2421 Lisp_Object tmp = args[0], ret;
2422 args[0] = args[1];
2423 args[1] = tmp;
2424 ret = Ffuncall (nargs, args);
2425 args[1] = args[0];
2426 args[0] = tmp;
2427 return ret;
2428 }
2429
2430 DEFUN ("run-hook-wrapped", Frun_hook_wrapped, Srun_hook_wrapped, 2, MANY, 0,
2431 doc: /* Run HOOK, passing each function through WRAP-FUNCTION.
2432 I.e. instead of calling each function FUN directly with arguments ARGS,
2433 it calls WRAP-FUNCTION with arguments FUN and ARGS.
2434 As soon as a call to WRAP-FUNCTION returns non-nil, `run-hook-wrapped'
2435 aborts and returns that value.
2436 usage: (run-hook-wrapped HOOK WRAP-FUNCTION &rest ARGS) */)
2437 (ptrdiff_t nargs, Lisp_Object *args)
2438 {
2439 return run_hook_with_args (nargs, args, run_hook_wrapped_funcall);
2440 }
2441
2442 /* ARGS[0] should be a hook symbol.
2443 Call each of the functions in the hook value, passing each of them
2444 as arguments all the rest of ARGS (all NARGS - 1 elements).
2445 FUNCALL specifies how to call each function on the hook. */
2446
2447 Lisp_Object
2448 run_hook_with_args (ptrdiff_t nargs, Lisp_Object *args,
2449 Lisp_Object (*funcall) (ptrdiff_t nargs, Lisp_Object *args))
2450 {
2451 Lisp_Object sym, val, ret = Qnil;
2452
2453 /* If we are dying or still initializing,
2454 don't do anything--it would probably crash if we tried. */
2455 if (NILP (Vrun_hooks))
2456 return Qnil;
2457
2458 sym = args[0];
2459 val = find_symbol_value (sym);
2460
2461 if (EQ (val, Qunbound) || NILP (val))
2462 return ret;
2463 else if (!CONSP (val) || FUNCTIONP (val))
2464 {
2465 args[0] = val;
2466 return funcall (nargs, args);
2467 }
2468 else
2469 {
2470 Lisp_Object global_vals = Qnil;
2471
2472 for (;
2473 CONSP (val) && NILP (ret);
2474 val = XCDR (val))
2475 {
2476 if (EQ (XCAR (val), Qt))
2477 {
2478 /* t indicates this hook has a local binding;
2479 it means to run the global binding too. */
2480 global_vals = Fdefault_value (sym);
2481 if (NILP (global_vals)) continue;
2482
2483 if (!CONSP (global_vals) || EQ (XCAR (global_vals), Qlambda))
2484 {
2485 args[0] = global_vals;
2486 ret = funcall (nargs, args);
2487 }
2488 else
2489 {
2490 for (;
2491 CONSP (global_vals) && NILP (ret);
2492 global_vals = XCDR (global_vals))
2493 {
2494 args[0] = XCAR (global_vals);
2495 /* In a global value, t should not occur. If it does, we
2496 must ignore it to avoid an endless loop. */
2497 if (!EQ (args[0], Qt))
2498 ret = funcall (nargs, args);
2499 }
2500 }
2501 }
2502 else
2503 {
2504 args[0] = XCAR (val);
2505 ret = funcall (nargs, args);
2506 }
2507 }
2508
2509 return ret;
2510 }
2511 }
2512
2513 /* Run the hook HOOK, giving each function no args. */
2514
2515 void
2516 run_hook (Lisp_Object hook)
2517 {
2518 Frun_hook_with_args (1, &hook);
2519 }
2520
2521 /* Run the hook HOOK, giving each function the two args ARG1 and ARG2. */
2522
2523 void
2524 run_hook_with_args_2 (Lisp_Object hook, Lisp_Object arg1, Lisp_Object arg2)
2525 {
2526 CALLN (Frun_hook_with_args, hook, arg1, arg2);
2527 }
2528
2529 /* Apply fn to arg. */
2530 Lisp_Object
2531 apply1 (Lisp_Object fn, Lisp_Object arg)
2532 {
2533 return NILP (arg) ? Ffuncall (1, &fn) : CALLN (Fapply, fn, arg);
2534 }
2535
2536 /* Call function fn on no arguments. */
2537 Lisp_Object
2538 call0 (Lisp_Object fn)
2539 {
2540 return Ffuncall (1, &fn);
2541 }
2542
2543 /* Call function fn with 1 argument arg1. */
2544 /* ARGSUSED */
2545 Lisp_Object
2546 call1 (Lisp_Object fn, Lisp_Object arg1)
2547 {
2548 return CALLN (Ffuncall, fn, arg1);
2549 }
2550
2551 /* Call function fn with 2 arguments arg1, arg2. */
2552 /* ARGSUSED */
2553 Lisp_Object
2554 call2 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2)
2555 {
2556 return CALLN (Ffuncall, fn, arg1, arg2);
2557 }
2558
2559 /* Call function fn with 3 arguments arg1, arg2, arg3. */
2560 /* ARGSUSED */
2561 Lisp_Object
2562 call3 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2563 {
2564 return CALLN (Ffuncall, fn, arg1, arg2, arg3);
2565 }
2566
2567 /* Call function fn with 4 arguments arg1, arg2, arg3, arg4. */
2568 /* ARGSUSED */
2569 Lisp_Object
2570 call4 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2571 Lisp_Object arg4)
2572 {
2573 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4);
2574 }
2575
2576 /* Call function fn with 5 arguments arg1, arg2, arg3, arg4, arg5. */
2577 /* ARGSUSED */
2578 Lisp_Object
2579 call5 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2580 Lisp_Object arg4, Lisp_Object arg5)
2581 {
2582 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5);
2583 }
2584
2585 /* Call function fn with 6 arguments arg1, arg2, arg3, arg4, arg5, arg6. */
2586 /* ARGSUSED */
2587 Lisp_Object
2588 call6 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2589 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6)
2590 {
2591 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6);
2592 }
2593
2594 /* Call function fn with 7 arguments arg1, arg2, arg3, arg4, arg5, arg6, arg7. */
2595 /* ARGSUSED */
2596 Lisp_Object
2597 call7 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2598 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6, Lisp_Object arg7)
2599 {
2600 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
2601 }
2602
2603 DEFUN ("functionp", Ffunctionp, Sfunctionp, 1, 1, 0,
2604 doc: /* Non-nil if OBJECT is a function. */)
2605 (Lisp_Object object)
2606 {
2607 if (FUNCTIONP (object))
2608 return Qt;
2609 return Qnil;
2610 }
2611
2612 DEFUN ("funcall", Ffuncall, Sfuncall, 1, MANY, 0,
2613 doc: /* Call first argument as a function, passing remaining arguments to it.
2614 Return the value that function returns.
2615 Thus, (funcall \\='cons \\='x \\='y) returns (x . y).
2616 usage: (funcall FUNCTION &rest ARGUMENTS) */)
2617 (ptrdiff_t nargs, Lisp_Object *args)
2618 {
2619 Lisp_Object fun, original_fun;
2620 Lisp_Object funcar;
2621 ptrdiff_t numargs = nargs - 1;
2622 Lisp_Object lisp_numargs;
2623 Lisp_Object val;
2624 Lisp_Object *internal_args;
2625 ptrdiff_t count;
2626
2627 QUIT;
2628
2629 if (++lisp_eval_depth > max_lisp_eval_depth)
2630 {
2631 if (max_lisp_eval_depth < 100)
2632 max_lisp_eval_depth = 100;
2633 if (lisp_eval_depth > max_lisp_eval_depth)
2634 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2635 }
2636
2637 count = record_in_backtrace (args[0], &args[1], nargs - 1);
2638
2639 maybe_gc ();
2640
2641 if (debug_on_next_call)
2642 do_debug_on_call (Qlambda, count);
2643
2644 check_cons_list ();
2645
2646 original_fun = args[0];
2647
2648 retry:
2649
2650 /* Optimize for no indirection. */
2651 fun = original_fun;
2652 if (SYMBOLP (fun) && !NILP (fun)
2653 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2654 fun = indirect_function (fun);
2655
2656 if (SUBRP (fun))
2657 {
2658 if (numargs < XSUBR (fun)->min_args
2659 || (XSUBR (fun)->max_args >= 0 && XSUBR (fun)->max_args < numargs))
2660 {
2661 XSETFASTINT (lisp_numargs, numargs);
2662 xsignal2 (Qwrong_number_of_arguments, original_fun, lisp_numargs);
2663 }
2664
2665 else if (XSUBR (fun)->max_args == UNEVALLED)
2666 xsignal1 (Qinvalid_function, original_fun);
2667
2668 else if (XSUBR (fun)->max_args == MANY)
2669 val = (XSUBR (fun)->function.aMANY) (numargs, args + 1);
2670 else
2671 {
2672 Lisp_Object internal_argbuf[8];
2673 if (XSUBR (fun)->max_args > numargs)
2674 {
2675 eassert (XSUBR (fun)->max_args <= ARRAYELTS (internal_argbuf));
2676 internal_args = internal_argbuf;
2677 memcpy (internal_args, args + 1, numargs * word_size);
2678 memclear (internal_args + numargs,
2679 (XSUBR (fun)->max_args - numargs) * word_size);
2680 }
2681 else
2682 internal_args = args + 1;
2683 switch (XSUBR (fun)->max_args)
2684 {
2685 case 0:
2686 val = (XSUBR (fun)->function.a0 ());
2687 break;
2688 case 1:
2689 val = (XSUBR (fun)->function.a1 (internal_args[0]));
2690 break;
2691 case 2:
2692 val = (XSUBR (fun)->function.a2
2693 (internal_args[0], internal_args[1]));
2694 break;
2695 case 3:
2696 val = (XSUBR (fun)->function.a3
2697 (internal_args[0], internal_args[1], internal_args[2]));
2698 break;
2699 case 4:
2700 val = (XSUBR (fun)->function.a4
2701 (internal_args[0], internal_args[1], internal_args[2],
2702 internal_args[3]));
2703 break;
2704 case 5:
2705 val = (XSUBR (fun)->function.a5
2706 (internal_args[0], internal_args[1], internal_args[2],
2707 internal_args[3], internal_args[4]));
2708 break;
2709 case 6:
2710 val = (XSUBR (fun)->function.a6
2711 (internal_args[0], internal_args[1], internal_args[2],
2712 internal_args[3], internal_args[4], internal_args[5]));
2713 break;
2714 case 7:
2715 val = (XSUBR (fun)->function.a7
2716 (internal_args[0], internal_args[1], internal_args[2],
2717 internal_args[3], internal_args[4], internal_args[5],
2718 internal_args[6]));
2719 break;
2720
2721 case 8:
2722 val = (XSUBR (fun)->function.a8
2723 (internal_args[0], internal_args[1], internal_args[2],
2724 internal_args[3], internal_args[4], internal_args[5],
2725 internal_args[6], internal_args[7]));
2726 break;
2727
2728 default:
2729
2730 /* If a subr takes more than 8 arguments without using MANY
2731 or UNEVALLED, we need to extend this function to support it.
2732 Until this is done, there is no way to call the function. */
2733 emacs_abort ();
2734 }
2735 }
2736 }
2737 else if (COMPILEDP (fun))
2738 val = funcall_lambda (fun, numargs, args + 1);
2739 else
2740 {
2741 if (NILP (fun))
2742 xsignal1 (Qvoid_function, original_fun);
2743 if (!CONSP (fun))
2744 xsignal1 (Qinvalid_function, original_fun);
2745 funcar = XCAR (fun);
2746 if (!SYMBOLP (funcar))
2747 xsignal1 (Qinvalid_function, original_fun);
2748 if (EQ (funcar, Qlambda)
2749 || EQ (funcar, Qclosure))
2750 val = funcall_lambda (fun, numargs, args + 1);
2751 else if (EQ (funcar, Qautoload))
2752 {
2753 Fautoload_do_load (fun, original_fun, Qnil);
2754 check_cons_list ();
2755 goto retry;
2756 }
2757 else
2758 xsignal1 (Qinvalid_function, original_fun);
2759 }
2760 check_cons_list ();
2761 lisp_eval_depth--;
2762 if (backtrace_debug_on_exit (specpdl + count))
2763 val = call_debugger (list2 (Qexit, val));
2764 specpdl_ptr--;
2765 return val;
2766 }
2767 \f
2768 static Lisp_Object
2769 apply_lambda (Lisp_Object fun, Lisp_Object args, ptrdiff_t count)
2770 {
2771 Lisp_Object args_left;
2772 ptrdiff_t i;
2773 EMACS_INT numargs;
2774 Lisp_Object *arg_vector;
2775 Lisp_Object tem;
2776 USE_SAFE_ALLOCA;
2777
2778 numargs = XFASTINT (Flength (args));
2779 SAFE_ALLOCA_LISP (arg_vector, numargs);
2780 args_left = args;
2781
2782 for (i = 0; i < numargs; )
2783 {
2784 tem = Fcar (args_left), args_left = Fcdr (args_left);
2785 tem = eval_sub (tem);
2786 arg_vector[i++] = tem;
2787 }
2788
2789 set_backtrace_args (specpdl + count, arg_vector, i);
2790 tem = funcall_lambda (fun, numargs, arg_vector);
2791
2792 check_cons_list ();
2793 lisp_eval_depth--;
2794 /* Do the debug-on-exit now, while arg_vector still exists. */
2795 if (backtrace_debug_on_exit (specpdl + count))
2796 tem = call_debugger (list2 (Qexit, tem));
2797 SAFE_FREE ();
2798 specpdl_ptr--;
2799 return tem;
2800 }
2801
2802 /* Apply a Lisp function FUN to the NARGS evaluated arguments in ARG_VECTOR
2803 and return the result of evaluation.
2804 FUN must be either a lambda-expression or a compiled-code object. */
2805
2806 static Lisp_Object
2807 funcall_lambda (Lisp_Object fun, ptrdiff_t nargs,
2808 register Lisp_Object *arg_vector)
2809 {
2810 Lisp_Object val, syms_left, next, lexenv;
2811 ptrdiff_t count = SPECPDL_INDEX ();
2812 ptrdiff_t i;
2813 bool optional, rest;
2814
2815 if (CONSP (fun))
2816 {
2817 if (EQ (XCAR (fun), Qclosure))
2818 {
2819 fun = XCDR (fun); /* Drop `closure'. */
2820 lexenv = XCAR (fun);
2821 CHECK_LIST_CONS (fun, fun);
2822 }
2823 else
2824 lexenv = Qnil;
2825 syms_left = XCDR (fun);
2826 if (CONSP (syms_left))
2827 syms_left = XCAR (syms_left);
2828 else
2829 xsignal1 (Qinvalid_function, fun);
2830 }
2831 else if (COMPILEDP (fun))
2832 {
2833 ptrdiff_t size = ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK;
2834 if (size <= COMPILED_STACK_DEPTH)
2835 xsignal1 (Qinvalid_function, fun);
2836 syms_left = AREF (fun, COMPILED_ARGLIST);
2837 if (INTEGERP (syms_left))
2838 /* A byte-code object with a non-nil `push args' slot means we
2839 shouldn't bind any arguments, instead just call the byte-code
2840 interpreter directly; it will push arguments as necessary.
2841
2842 Byte-code objects with either a non-existent, or a nil value for
2843 the `push args' slot (the default), have dynamically-bound
2844 arguments, and use the argument-binding code below instead (as do
2845 all interpreted functions, even lexically bound ones). */
2846 {
2847 /* If we have not actually read the bytecode string
2848 and constants vector yet, fetch them from the file. */
2849 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2850 Ffetch_bytecode (fun);
2851 return exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2852 AREF (fun, COMPILED_CONSTANTS),
2853 AREF (fun, COMPILED_STACK_DEPTH),
2854 syms_left,
2855 nargs, arg_vector);
2856 }
2857 lexenv = Qnil;
2858 }
2859 else
2860 emacs_abort ();
2861
2862 i = optional = rest = 0;
2863 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
2864 {
2865 QUIT;
2866
2867 next = XCAR (syms_left);
2868 if (!SYMBOLP (next))
2869 xsignal1 (Qinvalid_function, fun);
2870
2871 if (EQ (next, Qand_rest))
2872 rest = 1;
2873 else if (EQ (next, Qand_optional))
2874 optional = 1;
2875 else
2876 {
2877 Lisp_Object arg;
2878 if (rest)
2879 {
2880 arg = Flist (nargs - i, &arg_vector[i]);
2881 i = nargs;
2882 }
2883 else if (i < nargs)
2884 arg = arg_vector[i++];
2885 else if (!optional)
2886 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2887 else
2888 arg = Qnil;
2889
2890 /* Bind the argument. */
2891 if (!NILP (lexenv) && SYMBOLP (next))
2892 /* Lexically bind NEXT by adding it to the lexenv alist. */
2893 lexenv = Fcons (Fcons (next, arg), lexenv);
2894 else
2895 /* Dynamically bind NEXT. */
2896 specbind (next, arg);
2897 }
2898 }
2899
2900 if (!NILP (syms_left))
2901 xsignal1 (Qinvalid_function, fun);
2902 else if (i < nargs)
2903 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2904
2905 if (!EQ (lexenv, Vinternal_interpreter_environment))
2906 /* Instantiate a new lexical environment. */
2907 specbind (Qinternal_interpreter_environment, lexenv);
2908
2909 if (CONSP (fun))
2910 val = Fprogn (XCDR (XCDR (fun)));
2911 else
2912 {
2913 /* If we have not actually read the bytecode string
2914 and constants vector yet, fetch them from the file. */
2915 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2916 Ffetch_bytecode (fun);
2917 val = exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2918 AREF (fun, COMPILED_CONSTANTS),
2919 AREF (fun, COMPILED_STACK_DEPTH),
2920 Qnil, 0, 0);
2921 }
2922
2923 return unbind_to (count, val);
2924 }
2925
2926 DEFUN ("fetch-bytecode", Ffetch_bytecode, Sfetch_bytecode,
2927 1, 1, 0,
2928 doc: /* If byte-compiled OBJECT is lazy-loaded, fetch it now. */)
2929 (Lisp_Object object)
2930 {
2931 Lisp_Object tem;
2932
2933 if (COMPILEDP (object))
2934 {
2935 ptrdiff_t size = ASIZE (object) & PSEUDOVECTOR_SIZE_MASK;
2936 if (size <= COMPILED_STACK_DEPTH)
2937 xsignal1 (Qinvalid_function, object);
2938 if (CONSP (AREF (object, COMPILED_BYTECODE)))
2939 {
2940 tem = read_doc_string (AREF (object, COMPILED_BYTECODE));
2941 if (!CONSP (tem))
2942 {
2943 tem = AREF (object, COMPILED_BYTECODE);
2944 if (CONSP (tem) && STRINGP (XCAR (tem)))
2945 error ("Invalid byte code in %s", SDATA (XCAR (tem)));
2946 else
2947 error ("Invalid byte code");
2948 }
2949 ASET (object, COMPILED_BYTECODE, XCAR (tem));
2950 ASET (object, COMPILED_CONSTANTS, XCDR (tem));
2951 }
2952 }
2953 return object;
2954 }
2955 \f
2956 /* Return true if SYMBOL currently has a let-binding
2957 which was made in the buffer that is now current. */
2958
2959 bool
2960 let_shadows_buffer_binding_p (struct Lisp_Symbol *symbol)
2961 {
2962 union specbinding *p;
2963 Lisp_Object buf = Fcurrent_buffer ();
2964
2965 for (p = specpdl_ptr; p > specpdl; )
2966 if ((--p)->kind > SPECPDL_LET)
2967 {
2968 struct Lisp_Symbol *let_bound_symbol = XSYMBOL (specpdl_symbol (p));
2969 eassert (let_bound_symbol->redirect != SYMBOL_VARALIAS);
2970 if (symbol == let_bound_symbol
2971 && EQ (specpdl_where (p), buf))
2972 return 1;
2973 }
2974
2975 return 0;
2976 }
2977
2978 bool
2979 let_shadows_global_binding_p (Lisp_Object symbol)
2980 {
2981 union specbinding *p;
2982
2983 for (p = specpdl_ptr; p > specpdl; )
2984 if ((--p)->kind >= SPECPDL_LET && EQ (specpdl_symbol (p), symbol))
2985 return 1;
2986
2987 return 0;
2988 }
2989
2990 /* `specpdl_ptr' describes which variable is
2991 let-bound, so it can be properly undone when we unbind_to.
2992 It can be either a plain SPECPDL_LET or a SPECPDL_LET_LOCAL/DEFAULT.
2993 - SYMBOL is the variable being bound. Note that it should not be
2994 aliased (i.e. when let-binding V1 that's aliased to V2, we want
2995 to record V2 here).
2996 - WHERE tells us in which buffer the binding took place.
2997 This is used for SPECPDL_LET_LOCAL bindings (i.e. bindings to a
2998 buffer-local variable) as well as for SPECPDL_LET_DEFAULT bindings,
2999 i.e. bindings to the default value of a variable which can be
3000 buffer-local. */
3001
3002 void
3003 specbind (Lisp_Object symbol, Lisp_Object value)
3004 {
3005 struct Lisp_Symbol *sym;
3006
3007 CHECK_SYMBOL (symbol);
3008 sym = XSYMBOL (symbol);
3009
3010 start:
3011 switch (sym->redirect)
3012 {
3013 case SYMBOL_VARALIAS:
3014 sym = indirect_variable (sym); XSETSYMBOL (symbol, sym); goto start;
3015 case SYMBOL_PLAINVAL:
3016 /* The most common case is that of a non-constant symbol with a
3017 trivial value. Make that as fast as we can. */
3018 specpdl_ptr->let.kind = SPECPDL_LET;
3019 specpdl_ptr->let.symbol = symbol;
3020 specpdl_ptr->let.old_value = SYMBOL_VAL (sym);
3021 grow_specpdl ();
3022 if (!sym->constant)
3023 SET_SYMBOL_VAL (sym, value);
3024 else
3025 set_internal (symbol, value, Qnil, 1);
3026 break;
3027 case SYMBOL_LOCALIZED:
3028 if (SYMBOL_BLV (sym)->frame_local)
3029 error ("Frame-local vars cannot be let-bound");
3030 case SYMBOL_FORWARDED:
3031 {
3032 Lisp_Object ovalue = find_symbol_value (symbol);
3033 specpdl_ptr->let.kind = SPECPDL_LET_LOCAL;
3034 specpdl_ptr->let.symbol = symbol;
3035 specpdl_ptr->let.old_value = ovalue;
3036 specpdl_ptr->let.where = Fcurrent_buffer ();
3037
3038 eassert (sym->redirect != SYMBOL_LOCALIZED
3039 || (EQ (SYMBOL_BLV (sym)->where, Fcurrent_buffer ())));
3040
3041 if (sym->redirect == SYMBOL_LOCALIZED)
3042 {
3043 if (!blv_found (SYMBOL_BLV (sym)))
3044 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3045 }
3046 else if (BUFFER_OBJFWDP (SYMBOL_FWD (sym)))
3047 {
3048 /* If SYMBOL is a per-buffer variable which doesn't have a
3049 buffer-local value here, make the `let' change the global
3050 value by changing the value of SYMBOL in all buffers not
3051 having their own value. This is consistent with what
3052 happens with other buffer-local variables. */
3053 if (NILP (Flocal_variable_p (symbol, Qnil)))
3054 {
3055 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3056 grow_specpdl ();
3057 Fset_default (symbol, value);
3058 return;
3059 }
3060 }
3061 else
3062 specpdl_ptr->let.kind = SPECPDL_LET;
3063
3064 grow_specpdl ();
3065 set_internal (symbol, value, Qnil, 1);
3066 break;
3067 }
3068 default: emacs_abort ();
3069 }
3070 }
3071
3072 /* Push unwind-protect entries of various types. */
3073
3074 void
3075 record_unwind_protect (void (*function) (Lisp_Object), Lisp_Object arg)
3076 {
3077 specpdl_ptr->unwind.kind = SPECPDL_UNWIND;
3078 specpdl_ptr->unwind.func = function;
3079 specpdl_ptr->unwind.arg = arg;
3080 grow_specpdl ();
3081 }
3082
3083 void
3084 record_unwind_protect_ptr (void (*function) (void *), void *arg)
3085 {
3086 specpdl_ptr->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3087 specpdl_ptr->unwind_ptr.func = function;
3088 specpdl_ptr->unwind_ptr.arg = arg;
3089 grow_specpdl ();
3090 }
3091
3092 void
3093 record_unwind_protect_int (void (*function) (int), int arg)
3094 {
3095 specpdl_ptr->unwind_int.kind = SPECPDL_UNWIND_INT;
3096 specpdl_ptr->unwind_int.func = function;
3097 specpdl_ptr->unwind_int.arg = arg;
3098 grow_specpdl ();
3099 }
3100
3101 void
3102 record_unwind_protect_void (void (*function) (void))
3103 {
3104 specpdl_ptr->unwind_void.kind = SPECPDL_UNWIND_VOID;
3105 specpdl_ptr->unwind_void.func = function;
3106 grow_specpdl ();
3107 }
3108
3109 static void
3110 do_nothing (void)
3111 {}
3112
3113 /* Push an unwind-protect entry that does nothing, so that
3114 set_unwind_protect_ptr can overwrite it later. */
3115
3116 void
3117 record_unwind_protect_nothing (void)
3118 {
3119 record_unwind_protect_void (do_nothing);
3120 }
3121
3122 /* Clear the unwind-protect entry COUNT, so that it does nothing.
3123 It need not be at the top of the stack. */
3124
3125 void
3126 clear_unwind_protect (ptrdiff_t count)
3127 {
3128 union specbinding *p = specpdl + count;
3129 p->unwind_void.kind = SPECPDL_UNWIND_VOID;
3130 p->unwind_void.func = do_nothing;
3131 }
3132
3133 /* Set the unwind-protect entry COUNT so that it invokes FUNC (ARG).
3134 It need not be at the top of the stack. Discard the entry's
3135 previous value without invoking it. */
3136
3137 void
3138 set_unwind_protect (ptrdiff_t count, void (*func) (Lisp_Object),
3139 Lisp_Object arg)
3140 {
3141 union specbinding *p = specpdl + count;
3142 p->unwind.kind = SPECPDL_UNWIND;
3143 p->unwind.func = func;
3144 p->unwind.arg = arg;
3145 }
3146
3147 void
3148 set_unwind_protect_ptr (ptrdiff_t count, void (*func) (void *), void *arg)
3149 {
3150 union specbinding *p = specpdl + count;
3151 p->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3152 p->unwind_ptr.func = func;
3153 p->unwind_ptr.arg = arg;
3154 }
3155
3156 /* Pop and execute entries from the unwind-protect stack until the
3157 depth COUNT is reached. Return VALUE. */
3158
3159 Lisp_Object
3160 unbind_to (ptrdiff_t count, Lisp_Object value)
3161 {
3162 Lisp_Object quitf = Vquit_flag;
3163
3164 Vquit_flag = Qnil;
3165
3166 while (specpdl_ptr != specpdl + count)
3167 {
3168 /* Decrement specpdl_ptr before we do the work to unbind it, so
3169 that an error in unbinding won't try to unbind the same entry
3170 again. Take care to copy any parts of the binding needed
3171 before invoking any code that can make more bindings. */
3172
3173 specpdl_ptr--;
3174
3175 switch (specpdl_ptr->kind)
3176 {
3177 case SPECPDL_UNWIND:
3178 specpdl_ptr->unwind.func (specpdl_ptr->unwind.arg);
3179 break;
3180 case SPECPDL_UNWIND_PTR:
3181 specpdl_ptr->unwind_ptr.func (specpdl_ptr->unwind_ptr.arg);
3182 break;
3183 case SPECPDL_UNWIND_INT:
3184 specpdl_ptr->unwind_int.func (specpdl_ptr->unwind_int.arg);
3185 break;
3186 case SPECPDL_UNWIND_VOID:
3187 specpdl_ptr->unwind_void.func ();
3188 break;
3189 case SPECPDL_BACKTRACE:
3190 break;
3191 case SPECPDL_LET:
3192 { /* If variable has a trivial value (no forwarding), we can
3193 just set it. No need to check for constant symbols here,
3194 since that was already done by specbind. */
3195 struct Lisp_Symbol *sym = XSYMBOL (specpdl_symbol (specpdl_ptr));
3196 if (sym->redirect == SYMBOL_PLAINVAL)
3197 {
3198 SET_SYMBOL_VAL (sym, specpdl_old_value (specpdl_ptr));
3199 break;
3200 }
3201 else
3202 { /* FALLTHROUGH!!
3203 NOTE: we only ever come here if make_local_foo was used for
3204 the first time on this var within this let. */
3205 }
3206 }
3207 case SPECPDL_LET_DEFAULT:
3208 Fset_default (specpdl_symbol (specpdl_ptr),
3209 specpdl_old_value (specpdl_ptr));
3210 break;
3211 case SPECPDL_LET_LOCAL:
3212 {
3213 Lisp_Object symbol = specpdl_symbol (specpdl_ptr);
3214 Lisp_Object where = specpdl_where (specpdl_ptr);
3215 Lisp_Object old_value = specpdl_old_value (specpdl_ptr);
3216 eassert (BUFFERP (where));
3217
3218 /* If this was a local binding, reset the value in the appropriate
3219 buffer, but only if that buffer's binding still exists. */
3220 if (!NILP (Flocal_variable_p (symbol, where)))
3221 set_internal (symbol, old_value, where, 1);
3222 }
3223 break;
3224 }
3225 }
3226
3227 if (NILP (Vquit_flag) && !NILP (quitf))
3228 Vquit_flag = quitf;
3229
3230 return value;
3231 }
3232
3233 DEFUN ("special-variable-p", Fspecial_variable_p, Sspecial_variable_p, 1, 1, 0,
3234 doc: /* Return non-nil if SYMBOL's global binding has been declared special.
3235 A special variable is one that will be bound dynamically, even in a
3236 context where binding is lexical by default. */)
3237 (Lisp_Object symbol)
3238 {
3239 CHECK_SYMBOL (symbol);
3240 return XSYMBOL (symbol)->declared_special ? Qt : Qnil;
3241 }
3242
3243 \f
3244 DEFUN ("backtrace-debug", Fbacktrace_debug, Sbacktrace_debug, 2, 2, 0,
3245 doc: /* Set the debug-on-exit flag of eval frame LEVEL levels down to FLAG.
3246 The debugger is entered when that frame exits, if the flag is non-nil. */)
3247 (Lisp_Object level, Lisp_Object flag)
3248 {
3249 union specbinding *pdl = backtrace_top ();
3250 register EMACS_INT i;
3251
3252 CHECK_NUMBER (level);
3253
3254 for (i = 0; backtrace_p (pdl) && i < XINT (level); i++)
3255 pdl = backtrace_next (pdl);
3256
3257 if (backtrace_p (pdl))
3258 set_backtrace_debug_on_exit (pdl, !NILP (flag));
3259
3260 return flag;
3261 }
3262
3263 DEFUN ("backtrace", Fbacktrace, Sbacktrace, 0, 0, "",
3264 doc: /* Print a trace of Lisp function calls currently active.
3265 Output stream used is value of `standard-output'. */)
3266 (void)
3267 {
3268 union specbinding *pdl = backtrace_top ();
3269 Lisp_Object tem;
3270 Lisp_Object old_print_level = Vprint_level;
3271
3272 if (NILP (Vprint_level))
3273 XSETFASTINT (Vprint_level, 8);
3274
3275 while (backtrace_p (pdl))
3276 {
3277 write_string (backtrace_debug_on_exit (pdl) ? "* " : " ");
3278 if (backtrace_nargs (pdl) == UNEVALLED)
3279 {
3280 Fprin1 (Fcons (backtrace_function (pdl), *backtrace_args (pdl)),
3281 Qnil);
3282 write_string ("\n");
3283 }
3284 else
3285 {
3286 tem = backtrace_function (pdl);
3287 Fprin1 (tem, Qnil); /* This can QUIT. */
3288 write_string ("(");
3289 {
3290 ptrdiff_t i;
3291 for (i = 0; i < backtrace_nargs (pdl); i++)
3292 {
3293 if (i) write_string (" ");
3294 Fprin1 (backtrace_args (pdl)[i], Qnil);
3295 }
3296 }
3297 write_string (")\n");
3298 }
3299 pdl = backtrace_next (pdl);
3300 }
3301
3302 Vprint_level = old_print_level;
3303 return Qnil;
3304 }
3305
3306 static union specbinding *
3307 get_backtrace_frame (Lisp_Object nframes, Lisp_Object base)
3308 {
3309 union specbinding *pdl = backtrace_top ();
3310 register EMACS_INT i;
3311
3312 CHECK_NATNUM (nframes);
3313
3314 if (!NILP (base))
3315 { /* Skip up to `base'. */
3316 base = Findirect_function (base, Qt);
3317 while (backtrace_p (pdl)
3318 && !EQ (base, Findirect_function (backtrace_function (pdl), Qt)))
3319 pdl = backtrace_next (pdl);
3320 }
3321
3322 /* Find the frame requested. */
3323 for (i = XFASTINT (nframes); i > 0 && backtrace_p (pdl); i--)
3324 pdl = backtrace_next (pdl);
3325
3326 return pdl;
3327 }
3328
3329 DEFUN ("backtrace-frame", Fbacktrace_frame, Sbacktrace_frame, 1, 2, NULL,
3330 doc: /* Return the function and arguments NFRAMES up from current execution point.
3331 If that frame has not evaluated the arguments yet (or is a special form),
3332 the value is (nil FUNCTION ARG-FORMS...).
3333 If that frame has evaluated its arguments and called its function already,
3334 the value is (t FUNCTION ARG-VALUES...).
3335 A &rest arg is represented as the tail of the list ARG-VALUES.
3336 FUNCTION is whatever was supplied as car of evaluated list,
3337 or a lambda expression for macro calls.
3338 If NFRAMES is more than the number of frames, the value is nil.
3339 If BASE is non-nil, it should be a function and NFRAMES counts from its
3340 nearest activation frame. */)
3341 (Lisp_Object nframes, Lisp_Object base)
3342 {
3343 union specbinding *pdl = get_backtrace_frame (nframes, base);
3344
3345 if (!backtrace_p (pdl))
3346 return Qnil;
3347 if (backtrace_nargs (pdl) == UNEVALLED)
3348 return Fcons (Qnil,
3349 Fcons (backtrace_function (pdl), *backtrace_args (pdl)));
3350 else
3351 {
3352 Lisp_Object tem = Flist (backtrace_nargs (pdl), backtrace_args (pdl));
3353
3354 return Fcons (Qt, Fcons (backtrace_function (pdl), tem));
3355 }
3356 }
3357
3358 /* For backtrace-eval, we want to temporarily unwind the last few elements of
3359 the specpdl stack, and then rewind them. We store the pre-unwind values
3360 directly in the pre-existing specpdl elements (i.e. we swap the current
3361 value and the old value stored in the specpdl), kind of like the inplace
3362 pointer-reversal trick. As it turns out, the rewind does the same as the
3363 unwind, except it starts from the other end of the specpdl stack, so we use
3364 the same function for both unwind and rewind. */
3365 static void
3366 backtrace_eval_unrewind (int distance)
3367 {
3368 union specbinding *tmp = specpdl_ptr;
3369 int step = -1;
3370 if (distance < 0)
3371 { /* It's a rewind rather than unwind. */
3372 tmp += distance - 1;
3373 step = 1;
3374 distance = -distance;
3375 }
3376
3377 for (; distance > 0; distance--)
3378 {
3379 tmp += step;
3380 switch (tmp->kind)
3381 {
3382 /* FIXME: Ideally we'd like to "temporarily unwind" (some of) those
3383 unwind_protect, but the problem is that we don't know how to
3384 rewind them afterwards. */
3385 case SPECPDL_UNWIND:
3386 {
3387 Lisp_Object oldarg = tmp->unwind.arg;
3388 if (tmp->unwind.func == set_buffer_if_live)
3389 tmp->unwind.arg = Fcurrent_buffer ();
3390 else if (tmp->unwind.func == save_excursion_restore)
3391 tmp->unwind.arg = save_excursion_save ();
3392 else
3393 break;
3394 tmp->unwind.func (oldarg);
3395 break;
3396 }
3397
3398 case SPECPDL_UNWIND_PTR:
3399 case SPECPDL_UNWIND_INT:
3400 case SPECPDL_UNWIND_VOID:
3401 case SPECPDL_BACKTRACE:
3402 break;
3403 case SPECPDL_LET:
3404 { /* If variable has a trivial value (no forwarding), we can
3405 just set it. No need to check for constant symbols here,
3406 since that was already done by specbind. */
3407 struct Lisp_Symbol *sym = XSYMBOL (specpdl_symbol (tmp));
3408 if (sym->redirect == SYMBOL_PLAINVAL)
3409 {
3410 Lisp_Object old_value = specpdl_old_value (tmp);
3411 set_specpdl_old_value (tmp, SYMBOL_VAL (sym));
3412 SET_SYMBOL_VAL (sym, old_value);
3413 break;
3414 }
3415 else
3416 { /* FALLTHROUGH!!
3417 NOTE: we only ever come here if make_local_foo was used for
3418 the first time on this var within this let. */
3419 }
3420 }
3421 case SPECPDL_LET_DEFAULT:
3422 {
3423 Lisp_Object sym = specpdl_symbol (tmp);
3424 Lisp_Object old_value = specpdl_old_value (tmp);
3425 set_specpdl_old_value (tmp, Fdefault_value (sym));
3426 Fset_default (sym, old_value);
3427 }
3428 break;
3429 case SPECPDL_LET_LOCAL:
3430 {
3431 Lisp_Object symbol = specpdl_symbol (tmp);
3432 Lisp_Object where = specpdl_where (tmp);
3433 Lisp_Object old_value = specpdl_old_value (tmp);
3434 eassert (BUFFERP (where));
3435
3436 /* If this was a local binding, reset the value in the appropriate
3437 buffer, but only if that buffer's binding still exists. */
3438 if (!NILP (Flocal_variable_p (symbol, where)))
3439 {
3440 set_specpdl_old_value
3441 (tmp, Fbuffer_local_value (symbol, where));
3442 set_internal (symbol, old_value, where, 1);
3443 }
3444 }
3445 break;
3446 }
3447 }
3448 }
3449
3450 DEFUN ("backtrace-eval", Fbacktrace_eval, Sbacktrace_eval, 2, 3, NULL,
3451 doc: /* Evaluate EXP in the context of some activation frame.
3452 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3453 (Lisp_Object exp, Lisp_Object nframes, Lisp_Object base)
3454 {
3455 union specbinding *pdl = get_backtrace_frame (nframes, base);
3456 ptrdiff_t count = SPECPDL_INDEX ();
3457 ptrdiff_t distance = specpdl_ptr - pdl;
3458 eassert (distance >= 0);
3459
3460 if (!backtrace_p (pdl))
3461 error ("Activation frame not found!");
3462
3463 backtrace_eval_unrewind (distance);
3464 record_unwind_protect_int (backtrace_eval_unrewind, -distance);
3465
3466 /* Use eval_sub rather than Feval since the main motivation behind
3467 backtrace-eval is to be able to get/set the value of lexical variables
3468 from the debugger. */
3469 return unbind_to (count, eval_sub (exp));
3470 }
3471
3472 DEFUN ("backtrace--locals", Fbacktrace__locals, Sbacktrace__locals, 1, 2, NULL,
3473 doc: /* Return names and values of local variables of a stack frame.
3474 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3475 (Lisp_Object nframes, Lisp_Object base)
3476 {
3477 union specbinding *frame = get_backtrace_frame (nframes, base);
3478 union specbinding *prevframe
3479 = get_backtrace_frame (make_number (XFASTINT (nframes) - 1), base);
3480 ptrdiff_t distance = specpdl_ptr - frame;
3481 Lisp_Object result = Qnil;
3482 eassert (distance >= 0);
3483
3484 if (!backtrace_p (prevframe))
3485 error ("Activation frame not found!");
3486 if (!backtrace_p (frame))
3487 error ("Activation frame not found!");
3488
3489 /* The specpdl entries normally contain the symbol being bound along with its
3490 `old_value', so it can be restored. The new value to which it is bound is
3491 available in one of two places: either in the current value of the
3492 variable (if it hasn't been rebound yet) or in the `old_value' slot of the
3493 next specpdl entry for it.
3494 `backtrace_eval_unrewind' happens to swap the role of `old_value'
3495 and "new value", so we abuse it here, to fetch the new value.
3496 It's ugly (we'd rather not modify global data) and a bit inefficient,
3497 but it does the job for now. */
3498 backtrace_eval_unrewind (distance);
3499
3500 /* Grab values. */
3501 {
3502 union specbinding *tmp = prevframe;
3503 for (; tmp > frame; tmp--)
3504 {
3505 switch (tmp->kind)
3506 {
3507 case SPECPDL_LET:
3508 case SPECPDL_LET_DEFAULT:
3509 case SPECPDL_LET_LOCAL:
3510 {
3511 Lisp_Object sym = specpdl_symbol (tmp);
3512 Lisp_Object val = specpdl_old_value (tmp);
3513 if (EQ (sym, Qinternal_interpreter_environment))
3514 {
3515 Lisp_Object env = val;
3516 for (; CONSP (env); env = XCDR (env))
3517 {
3518 Lisp_Object binding = XCAR (env);
3519 if (CONSP (binding))
3520 result = Fcons (Fcons (XCAR (binding),
3521 XCDR (binding)),
3522 result);
3523 }
3524 }
3525 else
3526 result = Fcons (Fcons (sym, val), result);
3527 }
3528 break;
3529
3530 case SPECPDL_UNWIND:
3531 case SPECPDL_UNWIND_PTR:
3532 case SPECPDL_UNWIND_INT:
3533 case SPECPDL_UNWIND_VOID:
3534 case SPECPDL_BACKTRACE:
3535 break;
3536
3537 default:
3538 emacs_abort ();
3539 }
3540 }
3541 }
3542
3543 /* Restore values from specpdl to original place. */
3544 backtrace_eval_unrewind (-distance);
3545
3546 return result;
3547 }
3548
3549 \f
3550 void
3551 mark_specpdl (void)
3552 {
3553 union specbinding *pdl;
3554 for (pdl = specpdl; pdl != specpdl_ptr; pdl++)
3555 {
3556 switch (pdl->kind)
3557 {
3558 case SPECPDL_UNWIND:
3559 mark_object (specpdl_arg (pdl));
3560 break;
3561
3562 case SPECPDL_BACKTRACE:
3563 {
3564 ptrdiff_t nargs = backtrace_nargs (pdl);
3565 mark_object (backtrace_function (pdl));
3566 if (nargs == UNEVALLED)
3567 nargs = 1;
3568 while (nargs--)
3569 mark_object (backtrace_args (pdl)[nargs]);
3570 }
3571 break;
3572
3573 case SPECPDL_LET_DEFAULT:
3574 case SPECPDL_LET_LOCAL:
3575 mark_object (specpdl_where (pdl));
3576 /* Fall through. */
3577 case SPECPDL_LET:
3578 mark_object (specpdl_symbol (pdl));
3579 mark_object (specpdl_old_value (pdl));
3580 break;
3581
3582 case SPECPDL_UNWIND_PTR:
3583 case SPECPDL_UNWIND_INT:
3584 case SPECPDL_UNWIND_VOID:
3585 break;
3586
3587 default:
3588 emacs_abort ();
3589 }
3590 }
3591 }
3592
3593 void
3594 get_backtrace (Lisp_Object array)
3595 {
3596 union specbinding *pdl = backtrace_next (backtrace_top ());
3597 ptrdiff_t i = 0, asize = ASIZE (array);
3598
3599 /* Copy the backtrace contents into working memory. */
3600 for (; i < asize; i++)
3601 {
3602 if (backtrace_p (pdl))
3603 {
3604 ASET (array, i, backtrace_function (pdl));
3605 pdl = backtrace_next (pdl);
3606 }
3607 else
3608 ASET (array, i, Qnil);
3609 }
3610 }
3611
3612 Lisp_Object backtrace_top_function (void)
3613 {
3614 union specbinding *pdl = backtrace_top ();
3615 return (backtrace_p (pdl) ? backtrace_function (pdl) : Qnil);
3616 }
3617
3618 void
3619 syms_of_eval (void)
3620 {
3621 DEFVAR_INT ("max-specpdl-size", max_specpdl_size,
3622 doc: /* Limit on number of Lisp variable bindings and `unwind-protect's.
3623 If Lisp code tries to increase the total number past this amount,
3624 an error is signaled.
3625 You can safely use a value considerably larger than the default value,
3626 if that proves inconveniently small. However, if you increase it too far,
3627 Emacs could run out of memory trying to make the stack bigger.
3628 Note that this limit may be silently increased by the debugger
3629 if `debug-on-error' or `debug-on-quit' is set. */);
3630
3631 DEFVAR_INT ("max-lisp-eval-depth", max_lisp_eval_depth,
3632 doc: /* Limit on depth in `eval', `apply' and `funcall' before error.
3633
3634 This limit serves to catch infinite recursions for you before they cause
3635 actual stack overflow in C, which would be fatal for Emacs.
3636 You can safely make it considerably larger than its default value,
3637 if that proves inconveniently small. However, if you increase it too far,
3638 Emacs could overflow the real C stack, and crash. */);
3639
3640 DEFVAR_LISP ("quit-flag", Vquit_flag,
3641 doc: /* Non-nil causes `eval' to abort, unless `inhibit-quit' is non-nil.
3642 If the value is t, that means do an ordinary quit.
3643 If the value equals `throw-on-input', that means quit by throwing
3644 to the tag specified in `throw-on-input'; it's for handling `while-no-input'.
3645 Typing C-g sets `quit-flag' to t, regardless of `inhibit-quit',
3646 but `inhibit-quit' non-nil prevents anything from taking notice of that. */);
3647 Vquit_flag = Qnil;
3648
3649 DEFVAR_LISP ("inhibit-quit", Vinhibit_quit,
3650 doc: /* Non-nil inhibits C-g quitting from happening immediately.
3651 Note that `quit-flag' will still be set by typing C-g,
3652 so a quit will be signaled as soon as `inhibit-quit' is nil.
3653 To prevent this happening, set `quit-flag' to nil
3654 before making `inhibit-quit' nil. */);
3655 Vinhibit_quit = Qnil;
3656
3657 DEFSYM (Qinhibit_quit, "inhibit-quit");
3658 DEFSYM (Qautoload, "autoload");
3659 DEFSYM (Qinhibit_debugger, "inhibit-debugger");
3660 DEFSYM (Qmacro, "macro");
3661
3662 /* Note that the process handling also uses Qexit, but we don't want
3663 to staticpro it twice, so we just do it here. */
3664 DEFSYM (Qexit, "exit");
3665
3666 DEFSYM (Qinteractive, "interactive");
3667 DEFSYM (Qcommandp, "commandp");
3668 DEFSYM (Qand_rest, "&rest");
3669 DEFSYM (Qand_optional, "&optional");
3670 DEFSYM (Qclosure, "closure");
3671 DEFSYM (QCdocumentation, ":documentation");
3672 DEFSYM (Qdebug, "debug");
3673
3674 DEFVAR_LISP ("inhibit-debugger", Vinhibit_debugger,
3675 doc: /* Non-nil means never enter the debugger.
3676 Normally set while the debugger is already active, to avoid recursive
3677 invocations. */);
3678 Vinhibit_debugger = Qnil;
3679
3680 DEFVAR_LISP ("debug-on-error", Vdebug_on_error,
3681 doc: /* Non-nil means enter debugger if an error is signaled.
3682 Does not apply to errors handled by `condition-case' or those
3683 matched by `debug-ignored-errors'.
3684 If the value is a list, an error only means to enter the debugger
3685 if one of its condition symbols appears in the list.
3686 When you evaluate an expression interactively, this variable
3687 is temporarily non-nil if `eval-expression-debug-on-error' is non-nil.
3688 The command `toggle-debug-on-error' toggles this.
3689 See also the variable `debug-on-quit' and `inhibit-debugger'. */);
3690 Vdebug_on_error = Qnil;
3691
3692 DEFVAR_LISP ("debug-ignored-errors", Vdebug_ignored_errors,
3693 doc: /* List of errors for which the debugger should not be called.
3694 Each element may be a condition-name or a regexp that matches error messages.
3695 If any element applies to a given error, that error skips the debugger
3696 and just returns to top level.
3697 This overrides the variable `debug-on-error'.
3698 It does not apply to errors handled by `condition-case'. */);
3699 Vdebug_ignored_errors = Qnil;
3700
3701 DEFVAR_BOOL ("debug-on-quit", debug_on_quit,
3702 doc: /* Non-nil means enter debugger if quit is signaled (C-g, for example).
3703 Does not apply if quit is handled by a `condition-case'. */);
3704 debug_on_quit = 0;
3705
3706 DEFVAR_BOOL ("debug-on-next-call", debug_on_next_call,
3707 doc: /* Non-nil means enter debugger before next `eval', `apply' or `funcall'. */);
3708
3709 DEFVAR_BOOL ("debugger-may-continue", debugger_may_continue,
3710 doc: /* Non-nil means debugger may continue execution.
3711 This is nil when the debugger is called under circumstances where it
3712 might not be safe to continue. */);
3713 debugger_may_continue = 1;
3714
3715 DEFVAR_LISP ("debugger", Vdebugger,
3716 doc: /* Function to call to invoke debugger.
3717 If due to frame exit, args are `exit' and the value being returned;
3718 this function's value will be returned instead of that.
3719 If due to error, args are `error' and a list of the args to `signal'.
3720 If due to `apply' or `funcall' entry, one arg, `lambda'.
3721 If due to `eval' entry, one arg, t. */);
3722 Vdebugger = Qnil;
3723
3724 DEFVAR_LISP ("signal-hook-function", Vsignal_hook_function,
3725 doc: /* If non-nil, this is a function for `signal' to call.
3726 It receives the same arguments that `signal' was given.
3727 The Edebug package uses this to regain control. */);
3728 Vsignal_hook_function = Qnil;
3729
3730 DEFVAR_LISP ("debug-on-signal", Vdebug_on_signal,
3731 doc: /* Non-nil means call the debugger regardless of condition handlers.
3732 Note that `debug-on-error', `debug-on-quit' and friends
3733 still determine whether to handle the particular condition. */);
3734 Vdebug_on_signal = Qnil;
3735
3736 /* When lexical binding is being used,
3737 Vinternal_interpreter_environment is non-nil, and contains an alist
3738 of lexically-bound variable, or (t), indicating an empty
3739 environment. The lisp name of this variable would be
3740 `internal-interpreter-environment' if it weren't hidden.
3741 Every element of this list can be either a cons (VAR . VAL)
3742 specifying a lexical binding, or a single symbol VAR indicating
3743 that this variable should use dynamic scoping. */
3744 DEFSYM (Qinternal_interpreter_environment,
3745 "internal-interpreter-environment");
3746 DEFVAR_LISP ("internal-interpreter-environment",
3747 Vinternal_interpreter_environment,
3748 doc: /* If non-nil, the current lexical environment of the lisp interpreter.
3749 When lexical binding is not being used, this variable is nil.
3750 A value of `(t)' indicates an empty environment, otherwise it is an
3751 alist of active lexical bindings. */);
3752 Vinternal_interpreter_environment = Qnil;
3753 /* Don't export this variable to Elisp, so no one can mess with it
3754 (Just imagine if someone makes it buffer-local). */
3755 Funintern (Qinternal_interpreter_environment, Qnil);
3756
3757 Vrun_hooks = intern_c_string ("run-hooks");
3758 staticpro (&Vrun_hooks);
3759
3760 staticpro (&Vautoload_queue);
3761 Vautoload_queue = Qnil;
3762 staticpro (&Vsignaling_function);
3763 Vsignaling_function = Qnil;
3764
3765 inhibit_lisp_code = Qnil;
3766
3767 defsubr (&Sor);
3768 defsubr (&Sand);
3769 defsubr (&Sif);
3770 defsubr (&Scond);
3771 defsubr (&Sprogn);
3772 defsubr (&Sprog1);
3773 defsubr (&Sprog2);
3774 defsubr (&Ssetq);
3775 defsubr (&Squote);
3776 defsubr (&Sfunction);
3777 defsubr (&Sdefault_toplevel_value);
3778 defsubr (&Sset_default_toplevel_value);
3779 defsubr (&Sdefvar);
3780 defsubr (&Sdefvaralias);
3781 defsubr (&Sdefconst);
3782 defsubr (&Smake_var_non_special);
3783 defsubr (&Slet);
3784 defsubr (&SletX);
3785 defsubr (&Swhile);
3786 defsubr (&Smacroexpand);
3787 defsubr (&Scatch);
3788 defsubr (&Sthrow);
3789 defsubr (&Sunwind_protect);
3790 defsubr (&Scondition_case);
3791 defsubr (&Ssignal);
3792 defsubr (&Scommandp);
3793 defsubr (&Sautoload);
3794 defsubr (&Sautoload_do_load);
3795 defsubr (&Seval);
3796 defsubr (&Sapply);
3797 defsubr (&Sfuncall);
3798 defsubr (&Srun_hooks);
3799 defsubr (&Srun_hook_with_args);
3800 defsubr (&Srun_hook_with_args_until_success);
3801 defsubr (&Srun_hook_with_args_until_failure);
3802 defsubr (&Srun_hook_wrapped);
3803 defsubr (&Sfetch_bytecode);
3804 defsubr (&Sbacktrace_debug);
3805 defsubr (&Sbacktrace);
3806 defsubr (&Sbacktrace_frame);
3807 defsubr (&Sbacktrace_eval);
3808 defsubr (&Sbacktrace__locals);
3809 defsubr (&Sspecial_variable_p);
3810 defsubr (&Sfunctionp);
3811 }