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