eval.c 127 KB
Newer Older
Jim Blandy's avatar
Jim Blandy committed
1
/* Evaluator for GNU Emacs Lisp interpreter.
Glenn Morris's avatar
Glenn Morris committed
2

Paul Eggert's avatar
Paul Eggert committed
3
Copyright (C) 1985-1987, 1993-1995, 1999-2020 Free Software Foundation,
4
Inc.
Jim Blandy's avatar
Jim Blandy committed
5 6 7

This file is part of GNU Emacs.

8
GNU Emacs is free software: you can redistribute it and/or modify
Jim Blandy's avatar
Jim Blandy committed
9
it under the terms of the GNU General Public License as published by
10 11
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
Jim Blandy's avatar
Jim Blandy committed
12 13 14 15 16 17 18

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
19
along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */
Jim Blandy's avatar
Jim Blandy committed
20 21


22
#include <config.h>
23
#include <limits.h>
Paul Eggert's avatar
Paul Eggert committed
24
#include <stdlib.h>
Jim Blandy's avatar
Jim Blandy committed
25
#include "lisp.h"
26
#include "blockinput.h"
Jim Blandy's avatar
Jim Blandy committed
27
#include "commands.h"
Jim Blandy's avatar
Jim Blandy committed
28
#include "keyboard.h"
29
#include "dispextern.h"
30
#include "buffer.h"
Daniel Colascione's avatar
Daniel Colascione committed
31
#include "pdumper.h"
32

33 34 35 36 37 38 39 40 41
/* CACHEABLE is ordinarily nothing, except it is 'volatile' if
   necessary to cajole GCC into not warning incorrectly that a
   variable should be volatile.  */
#if defined GCC_LINT || defined lint
# define CACHEABLE volatile
#else
# define CACHEABLE /* empty */
#endif

Jim Blandy's avatar
Jim Blandy committed
42 43 44
/* Non-nil means record all fset's and provide's, to be undone
   if the file being autoloaded is not fully loaded.
   They are recorded by being consed onto the front of Vautoload_queue:
45
   (FUN . ODEF) for a defun, (0 . OFEATURES) for a provide.  */
Jim Blandy's avatar
Jim Blandy committed
46 47 48

Lisp_Object Vautoload_queue;

49 50 51 52 53
/* This holds either the symbol `run-hooks' or nil.
   It is nil at an early stage of startup, and when Emacs
   is shutting down.  */
Lisp_Object Vrun_hooks;

54 55
/* The function from which the last `signal' was called.  Set in
   Fsignal.  */
56
/* FIXME: We should probably get rid of this!  */
57 58
Lisp_Object Vsignaling_function;

59 60 61 62 63 64 65
/* These would ordinarily be static, but they need to be visible to GDB.  */
bool backtrace_p (union specbinding *) EXTERNALLY_VISIBLE;
Lisp_Object *backtrace_args (union specbinding *) EXTERNALLY_VISIBLE;
Lisp_Object backtrace_function (union specbinding *) EXTERNALLY_VISIBLE;
union specbinding *backtrace_next (union specbinding *) EXTERNALLY_VISIBLE;
union specbinding *backtrace_top (void) EXTERNALLY_VISIBLE;

66
static Lisp_Object funcall_lambda (Lisp_Object, ptrdiff_t, Lisp_Object *);
67
static Lisp_Object apply_lambda (Lisp_Object, Lisp_Object, ptrdiff_t);
Paul Pogonyshev's avatar
Paul Pogonyshev committed
68
static Lisp_Object lambda_arity (Lisp_Object);
69

70
static Lisp_Object
71
specpdl_symbol (union specbinding *pdl)
72 73
{
  eassert (pdl->kind >= SPECPDL_LET);
74
  return pdl->let.symbol;
75 76
}

77 78 79 80 81 82 83
static enum specbind_tag
specpdl_kind (union specbinding *pdl)
{
  eassert (pdl->kind >= SPECPDL_LET);
  return pdl->let.kind;
}

84
static Lisp_Object
85
specpdl_old_value (union specbinding *pdl)
86 87
{
  eassert (pdl->kind >= SPECPDL_LET);
88
  return pdl->let.old_value;
89 90
}

91 92 93 94 95 96 97
static void
set_specpdl_old_value (union specbinding *pdl, Lisp_Object val)
{
  eassert (pdl->kind >= SPECPDL_LET);
  pdl->let.old_value = val;
}

98
static Lisp_Object
99
specpdl_where (union specbinding *pdl)
100 101
{
  eassert (pdl->kind > SPECPDL_LET);
102
  return pdl->let.where;
103 104
}

Tom Tromey's avatar
Tom Tromey committed
105 106 107 108 109 110 111
static Lisp_Object
specpdl_saved_value (union specbinding *pdl)
{
  eassert (pdl->kind >= SPECPDL_LET);
  return pdl->let.saved_value;
}

112
static Lisp_Object
113
specpdl_arg (union specbinding *pdl)
114 115
{
  eassert (pdl->kind == SPECPDL_UNWIND);
116
  return pdl->unwind.arg;
117 118
}

119
Lisp_Object
120
backtrace_function (union specbinding *pdl)
121 122
{
  eassert (pdl->kind == SPECPDL_BACKTRACE);
123
  return pdl->bt.function;
124 125 126
}

static ptrdiff_t
127
backtrace_nargs (union specbinding *pdl)
128 129
{
  eassert (pdl->kind == SPECPDL_BACKTRACE);
130
  return pdl->bt.nargs;
131 132
}

133
Lisp_Object *
134
backtrace_args (union specbinding *pdl)
135 136
{
  eassert (pdl->kind == SPECPDL_BACKTRACE);
137
  return pdl->bt.args;
138 139 140
}

static bool
141
backtrace_debug_on_exit (union specbinding *pdl)
142 143
{
  eassert (pdl->kind == SPECPDL_BACKTRACE);
144
  return pdl->bt.debug_on_exit;
145 146
}

147
/* Functions to modify slots of backtrace records.  */
148

149
static void
150
set_backtrace_args (union specbinding *pdl, Lisp_Object *args, ptrdiff_t nargs)
151 152 153
{
  eassert (pdl->kind == SPECPDL_BACKTRACE);
  pdl->bt.args = args;
154
  pdl->bt.nargs = nargs;
155
}
156

157
static void
158 159 160 161 162
set_backtrace_debug_on_exit (union specbinding *pdl, bool doe)
{
  eassert (pdl->kind == SPECPDL_BACKTRACE);
  pdl->bt.debug_on_exit = doe;
}
163 164 165

/* Helper functions to scan the backtrace.  */

166 167
bool
backtrace_p (union specbinding *pdl)
168
{ return specpdl ? pdl >= specpdl : false; }
169

170 171 172 173
static bool
backtrace_thread_p (struct thread_state *tstate, union specbinding *pdl)
{ return pdl >= tstate->m_specpdl; }

174
union specbinding *
175
backtrace_top (void)
176
{
177 178 179 180 181 182
  /* This is so "xbacktrace" doesn't crash in pdumped Emacs if they
     invoke the command before init_eval_once_for_pdumper initializes
     specpdl machinery.  See also backtrace_p above.  */
  if (!specpdl)
    return NULL;

183
  union specbinding *pdl = specpdl_ptr - 1;
184
  while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
185 186
    pdl--;
  return pdl;
187
}
188

189 190 191 192 193 194 195 196 197
static union specbinding *
backtrace_thread_top (struct thread_state *tstate)
{
  union specbinding *pdl = tstate->m_specpdl_ptr - 1;
  while (backtrace_thread_p (tstate, pdl) && pdl->kind != SPECPDL_BACKTRACE)
    pdl--;
  return pdl;
}

198 199
union specbinding *
backtrace_next (union specbinding *pdl)
200
{
201 202 203 204
  pdl--;
  while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
    pdl--;
  return pdl;
205 206
}

Daniel Colascione's avatar
Daniel Colascione committed
207 208
static void init_eval_once_for_pdumper (void);

209 210 211 212 213 214 215 216 217
static union specbinding *
backtrace_thread_next (struct thread_state *tstate, union specbinding *pdl)
{
  pdl--;
  while (backtrace_thread_p (tstate, pdl) && pdl->kind != SPECPDL_BACKTRACE)
    pdl--;
  return pdl;
}

Andreas Schwab's avatar
Andreas Schwab committed
218
void
219
init_eval_once (void)
Jim Blandy's avatar
Jim Blandy committed
220
{
221
  /* Don't forget to update docs (lispref node "Local Variables").  */
222
  max_specpdl_size = 1600; /* 1500 is not enough for cl-generic.el.  */
223
  max_lisp_eval_depth = 800;
224
  Vrun_hooks = Qnil;
Daniel Colascione's avatar
Daniel Colascione committed
225 226 227 228 229 230 231 232 233 234
  pdumper_do_now_and_after_load (init_eval_once_for_pdumper);
}

static void
init_eval_once_for_pdumper (void)
{
  enum { size = 50 };
  union specbinding *pdlvec = malloc ((size + 1) * sizeof *specpdl);
  specpdl_size = size;
  specpdl = specpdl_ptr = pdlvec + 1;
Jim Blandy's avatar
Jim Blandy committed
235 236
}

Andreas Schwab's avatar
Andreas Schwab committed
237
void
238
init_eval (void)
Jim Blandy's avatar
Jim Blandy committed
239 240
{
  specpdl_ptr = specpdl;
241 242 243
  { /* Put a dummy catcher at top-level so that handlerlist is never NULL.
       This is important since handlerlist->nextfree holds the freelist
       which would otherwise leak every time we unwind back to top-level.   */
Ken Raeburn's avatar
Ken Raeburn committed
244 245
    handlerlist_sentinel = xzalloc (sizeof (struct handler));
    handlerlist = handlerlist_sentinel->nextfree = handlerlist_sentinel;
246
    struct handler *c = push_handler (Qunbound, CATCHER);
Ken Raeburn's avatar
Ken Raeburn committed
247 248 249
    eassert (c == handlerlist_sentinel);
    handlerlist_sentinel->nextfree = NULL;
    handlerlist_sentinel->next = NULL;
250
  }
Jim Blandy's avatar
Jim Blandy committed
251 252 253
  Vquit_flag = Qnil;
  debug_on_next_call = 0;
  lisp_eval_depth = 0;
254
  /* This is less than the initial value of num_nonmacro_input_events.  */
255
  when_entered_debugger = -1;
Jim Blandy's avatar
Jim Blandy committed
256 257
}

258 259 260 261 262 263 264 265 266 267
/* Ensure that *M is at least A + B if possible, or is its maximum
   value otherwise.  */

static void
max_ensure_room (intmax_t *m, intmax_t a, intmax_t b)
{
  intmax_t sum = INT_ADD_WRAPV (a, b, &sum) ? INTMAX_MAX : sum;
  *m = max (*m, sum);
}

268
/* Unwind-protect function used by call_debugger.  */
269

270
static void
271
restore_stack_limits (Lisp_Object data)
272
{
273 274
  integer_to_intmax (XCAR (data), &max_specpdl_size);
  integer_to_intmax (XCDR (data), &max_lisp_eval_depth);
275 276
}

277 278
static void grow_specpdl (void);

279 280
/* Call the Lisp debugger, giving it argument ARG.  */

281
Lisp_Object
282
call_debugger (Lisp_Object arg)
Jim Blandy's avatar
Jim Blandy committed
283
{
284
  bool debug_while_redisplaying;
285
  ptrdiff_t count = SPECPDL_INDEX ();
286
  Lisp_Object val;
287
  intmax_t old_depth = max_lisp_eval_depth;
288
  /* Do not allow max_specpdl_size less than actual depth (Bug#16603).  */
289
  intmax_t old_max = max (max_specpdl_size, count);
290

291 292 293 294
  /* The previous value of 40 is too small now that the debugger
     prints using cl-prin1 instead of prin1.  Printing lists nested 8
     deep (which is the value of print-level used in the debugger)
     currently requires 77 additional frames.  See bug#31919.  */
295
  max_ensure_room (&max_lisp_eval_depth, lisp_eval_depth, 100);
296

297 298
  /* While debugging Bug#16603, previous value of 100 was found
     too small to avoid specpdl overflow in the debugger itself.  */
299
  max_ensure_room (&max_specpdl_size, count, 200);
300 301 302 303 304 305 306 307 308 309

  if (old_max == count)
    {
      /* We can enter the debugger due to specpdl overflow (Bug#16603).  */
      specpdl_ptr--;
      grow_specpdl ();
    }

  /* Restore limits after leaving the debugger.  */
  record_unwind_protect (restore_stack_limits,
310
			 Fcons (make_int (old_max), make_int (old_depth)));
311

312
#ifdef HAVE_WINDOW_SYSTEM
313 314
  if (display_hourglass_p)
    cancel_hourglass ();
315 316
#endif

Jim Blandy's avatar
Jim Blandy committed
317
  debug_on_next_call = 0;
318
  when_entered_debugger = num_nonmacro_input_events;
319 320 321 322 323

  /* Resetting redisplaying_p to 0 makes sure that debug output is
     displayed if the debugger is invoked during redisplay.  */
  debug_while_redisplaying = redisplaying_p;
  redisplaying_p = 0;
324 325
  specbind (intern ("debugger-may-continue"),
	    debug_while_redisplaying ? Qnil : Qt);
326
  specbind (Qinhibit_redisplay, Qnil);
327
  specbind (Qinhibit_debugger, Qt);
328

329 330 331 332 333
  /* If we are debugging an error while `inhibit-changing-match-data'
     is bound to non-nil (e.g., within a call to `string-match-p'),
     then make sure debugger code can still use match data.  */
  specbind (Qinhibit_changing_match_data, Qnil);

334 335
#if 0 /* Binding this prevents execution of Lisp code during
	 redisplay, which necessarily leads to display problems.  */
336
  specbind (Qinhibit_eval_during_redisplay, Qt);
337
#endif
338

339 340 341 342
  val = apply1 (Vdebugger, arg);

  /* Interrupting redisplay and resuming it later is not safe under
     all circumstances.  So, when the debugger returns, abort the
343
     interrupted redisplay by going back to the top-level.  */
344 345 346
  if (debug_while_redisplaying)
    Ftop_level ();

347
  return unbind_to (count, val);
Jim Blandy's avatar
Jim Blandy committed
348 349
}

350
static void
351
do_debug_on_call (Lisp_Object code, ptrdiff_t count)
Jim Blandy's avatar
Jim Blandy committed
352 353
{
  debug_on_next_call = 0;
354
  set_backtrace_debug_on_exit (specpdl + count, true);
355
  call_debugger (list1 (code));
Jim Blandy's avatar
Jim Blandy committed
356 357 358 359 360 361 362
}

/* NOTE!!! Every function that can call EVAL must protect its args
   and temporaries from garbage collection while it needs them.
   The definition of `For' shows what you have to do.  */

DEFUN ("or", For, Sor, 0, UNEVALLED, 0,
Pavel Janík's avatar
Pavel Janík committed
363 364 365
       doc: /* Eval args until one of them yields non-nil, then return that value.
The remaining args are not evalled at all.
If all args return nil, return nil.
Juanma Barranquero's avatar
Juanma Barranquero committed
366
usage: (or CONDITIONS...)  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
367
  (Lisp_Object args)
Jim Blandy's avatar
Jim Blandy committed
368
{
369
  Lisp_Object val = Qnil;
Jim Blandy's avatar
Jim Blandy committed
370

371
  while (CONSP (args))
Jim Blandy's avatar
Jim Blandy committed
372
    {
373 374 375
      Lisp_Object arg = XCAR (args);
      args = XCDR (args);
      val = eval_sub (arg);
Jim Blandy's avatar
Jim Blandy committed
376
      if (!NILP (val))
Jim Blandy's avatar
Jim Blandy committed
377 378 379 380 381 382 383
	break;
    }

  return val;
}

DEFUN ("and", Fand, Sand, 0, UNEVALLED, 0,
Pavel Janík's avatar
Pavel Janík committed
384
       doc: /* Eval args until one of them yields nil, then return nil.
Pavel Janík's avatar
Pavel Janík committed
385 386
The remaining args are not evalled at all.
If no arg yields nil, return the last arg's value.
Juanma Barranquero's avatar
Juanma Barranquero committed
387
usage: (and CONDITIONS...)  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
388
  (Lisp_Object args)
Jim Blandy's avatar
Jim Blandy committed
389
{
390
  Lisp_Object val = Qt;
Jim Blandy's avatar
Jim Blandy committed
391

392
  while (CONSP (args))
Jim Blandy's avatar
Jim Blandy committed
393
    {
394 395 396
      Lisp_Object arg = XCAR (args);
      args = XCDR (args);
      val = eval_sub (arg);
Jim Blandy's avatar
Jim Blandy committed
397
      if (NILP (val))
Jim Blandy's avatar
Jim Blandy committed
398 399 400 401 402 403 404
	break;
    }

  return val;
}

DEFUN ("if", Fif, Sif, 2, UNEVALLED, 0,
Pavel Janík's avatar
Pavel Janík committed
405
       doc: /* If COND yields non-nil, do THEN, else do ELSE...
Pavel Janík's avatar
Pavel Janík committed
406 407 408
Returns the value of THEN or the value of the last of the ELSE's.
THEN must be one expression, but ELSE... can be zero or more expressions.
If COND yields nil, and there are no ELSE's, the value is nil.
409
usage: (if COND THEN ELSE...)  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
410
  (Lisp_Object args)
Jim Blandy's avatar
Jim Blandy committed
411
{
412
  Lisp_Object cond;
Jim Blandy's avatar
Jim Blandy committed
413

414
  cond = eval_sub (XCAR (args));
Jim Blandy's avatar
Jim Blandy committed
415

Jim Blandy's avatar
Jim Blandy committed
416
  if (!NILP (cond))
417
    return eval_sub (Fcar (XCDR (args)));
418
  return Fprogn (Fcdr (XCDR (args)));
Jim Blandy's avatar
Jim Blandy committed
419 420 421
}

DEFUN ("cond", Fcond, Scond, 0, UNEVALLED, 0,
Pavel Janík's avatar
Pavel Janík committed
422 423 424 425 426
       doc: /* Try each clause until one succeeds.
Each clause looks like (CONDITION BODY...).  CONDITION is evaluated
and, if the value is non-nil, this clause succeeds:
then the expressions in BODY are evaluated and the last one's
value is the value of the cond-form.
Glenn Morris's avatar
Glenn Morris committed
427 428
If a clause has one element, as in (CONDITION), then the cond-form
returns CONDITION's value, if that is non-nil.
Pavel Janík's avatar
Pavel Janík committed
429
If no clause succeeds, cond returns nil.
430
usage: (cond CLAUSES...)  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
431
  (Lisp_Object args)
Jim Blandy's avatar
Jim Blandy committed
432
{
433
  Lisp_Object val = args;
Jim Blandy's avatar
Jim Blandy committed
434

435
  while (CONSP (args))
Jim Blandy's avatar
Jim Blandy committed
436
    {
437
      Lisp_Object clause = XCAR (args);
438
      val = eval_sub (Fcar (clause));
Jim Blandy's avatar
Jim Blandy committed
439
      if (!NILP (val))
Jim Blandy's avatar
Jim Blandy committed
440
	{
441
	  if (!NILP (XCDR (clause)))
442
	    val = Fprogn (XCDR (clause));
Jim Blandy's avatar
Jim Blandy committed
443 444
	  break;
	}
445
      args = XCDR (args);
Jim Blandy's avatar
Jim Blandy committed
446 447 448 449 450
    }

  return val;
}

Paul Eggert's avatar
Paul Eggert committed
451
DEFUN ("progn", Fprogn, Sprogn, 0, UNEVALLED, 0,
Pavel Janík's avatar
Pavel Janík committed
452
       doc: /* Eval BODY forms sequentially and return value of last one.
Juanma Barranquero's avatar
Juanma Barranquero committed
453
usage: (progn BODY...)  */)
454
  (Lisp_Object body)
Jim Blandy's avatar
Jim Blandy committed
455
{
456
  Lisp_Object val = Qnil;
Jim Blandy's avatar
Jim Blandy committed
457

458
  while (CONSP (body))
Jim Blandy's avatar
Jim Blandy committed
459
    {
460
      Lisp_Object form = XCAR (body);
461
      body = XCDR (body);
462
      val = eval_sub (form);
Jim Blandy's avatar
Jim Blandy committed
463 464 465 466 467
    }

  return val;
}

Paul Eggert's avatar
Paul Eggert committed
468
/* Evaluate BODY sequentially, discarding its value.  */
469 470

void
Paul Eggert's avatar
Paul Eggert committed
471
prog_ignore (Lisp_Object body)
472 473 474 475
{
  Fprogn (body);
}

Jim Blandy's avatar
Jim Blandy committed
476
DEFUN ("prog1", Fprog1, Sprog1, 1, UNEVALLED, 0,
477
       doc: /* Eval FIRST and BODY sequentially; return value from FIRST.
Pavel Janík's avatar
Pavel Janík committed
478 479
The value of FIRST is saved during the evaluation of the remaining args,
whose values are discarded.
480
usage: (prog1 FIRST BODY...)  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
481
  (Lisp_Object args)
Jim Blandy's avatar
Jim Blandy committed
482
{
Paul Eggert's avatar
Paul Eggert committed
483 484
  Lisp_Object val = eval_sub (XCAR (args));
  prog_ignore (XCDR (args));
Jim Blandy's avatar
Jim Blandy committed
485 486 487 488
  return val;
}

DEFUN ("setq", Fsetq, Ssetq, 0, UNEVALLED, 0,
Pavel Janík's avatar
Pavel Janík committed
489 490 491 492 493 494 495
       doc: /* Set each SYM to the value of its VAL.
The symbols SYM are variables; they are literal (not evaluated).
The values VAL are expressions; they are evaluated.
Thus, (setq x (1+ y)) sets `x' to the value of `(1+ y)'.
The second VAL is not computed until after the first SYM is set, and so on;
each VAL can use the new value of variables set earlier in the `setq'.
The return value of the `setq' form is the value of the last VAL.
Juanma Barranquero's avatar
Juanma Barranquero committed
496
usage: (setq [SYM VAL]...)  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
497
  (Lisp_Object args)
Jim Blandy's avatar
Jim Blandy committed
498
{
499
  Lisp_Object val = args, tail = args;
Jim Blandy's avatar
Jim Blandy committed
500

501
  for (EMACS_INT nargs = 0; CONSP (tail); nargs += 2)
502
    {
503
      Lisp_Object sym = XCAR (tail);
504 505
      tail = XCDR (tail);
      if (!CONSP (tail))
506
	xsignal2 (Qwrong_number_of_arguments, Qsetq, make_fixnum (nargs + 1));
507 508 509 510 511
      Lisp_Object arg = XCAR (tail);
      tail = XCDR (tail);
      val = eval_sub (arg);
      /* Like for eval_sub, we do not check declared_special here since
	 it's been done when let-binding.  */
512 513 514
      Lisp_Object lex_binding
	= ((!NILP (Vinternal_interpreter_environment) /* Mere optimization!  */
	    && SYMBOLP (sym))
515
	   ? Fassq (sym, Vinternal_interpreter_environment)
516 517
	   : Qnil);
      if (!NILP (lex_binding))
518 519 520
	XSETCDR (lex_binding, val); /* SYM is lexically bound.  */
      else
	Fset (sym, val);	/* SYM is dynamically bound.  */
Jim Blandy's avatar
Jim Blandy committed
521 522 523 524
    }

  return val;
}
525

Jim Blandy's avatar
Jim Blandy committed
526
DEFUN ("quote", Fquote, Squote, 1, UNEVALLED, 0,
Pavel Janík's avatar
Pavel Janík committed
527
       doc: /* Return the argument, without evaluating it.  `(quote x)' yields `x'.
528 529 530
Warning: `quote' does not construct its return value, but just returns
the value that was pre-constructed by the Lisp reader (see info node
`(elisp)Printed Representation').
531
This means that \\='(a . b) is not identical to (cons \\='a \\='b): the former
532 533 534 535
does not cons.  Quoting should be reserved for constants that will
never be modified by side-effects, unless you like self-modifying code.
See the common pitfall in info node `(elisp)Rearrangement' for an example
of unexpected results when a quoted object is modified.
Pavel Janík's avatar
Pavel Janík committed
536
usage: (quote ARG)  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
537
  (Lisp_Object args)
Jim Blandy's avatar
Jim Blandy committed
538
{
539
  if (!NILP (XCDR (args)))
540
    xsignal2 (Qwrong_number_of_arguments, Qquote, Flength (args));
541
  return XCAR (args);
Jim Blandy's avatar
Jim Blandy committed
542
}
543

Jim Blandy's avatar
Jim Blandy committed
544
DEFUN ("function", Ffunction, Sfunction, 1, UNEVALLED, 0,
Pavel Janík's avatar
Pavel Janík committed
545
       doc: /* Like `quote', but preferred for objects which are functions.
546 547
In byte compilation, `function' causes its argument to be handled by
the byte compiler.  `quote' cannot do that.
Pavel Janík's avatar
Pavel Janík committed
548
usage: (function ARG)  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
549
  (Lisp_Object args)
Jim Blandy's avatar
Jim Blandy committed
550
{
551 552
  Lisp_Object quoted = XCAR (args);

553
  if (!NILP (XCDR (args)))
554
    xsignal2 (Qwrong_number_of_arguments, Qfunction, Flength (args));
555 556 557 558

  if (!NILP (Vinternal_interpreter_environment)
      && CONSP (quoted)
      && EQ (XCAR (quoted), Qlambda))
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
    { /* This is a lambda expression within a lexical environment;
	 return an interpreted closure instead of a simple lambda.  */
      Lisp_Object cdr = XCDR (quoted);
      Lisp_Object tmp = cdr;
      if (CONSP (tmp)
	  && (tmp = XCDR (tmp), CONSP (tmp))
	  && (tmp = XCAR (tmp), CONSP (tmp))
	  && (EQ (QCdocumentation, XCAR (tmp))))
	{ /* Handle the special (:documentation <form>) to build the docstring
	     dynamically.  */
	  Lisp_Object docstring = eval_sub (Fcar (XCDR (tmp)));
	  CHECK_STRING (docstring);
	  cdr = Fcons (XCAR (cdr), Fcons (docstring, XCDR (XCDR (cdr))));
	}
      return Fcons (Qclosure, Fcons (Vinternal_interpreter_environment,
				     cdr));
    }
576 577 578
  else
    /* Simply quote the argument.  */
    return quoted;
Jim Blandy's avatar
Jim Blandy committed
579 580
}

581

582
DEFUN ("defvaralias", Fdefvaralias, Sdefvaralias, 2, 3, 0,
583
       doc: /* Make NEW-ALIAS a variable alias for symbol BASE-VARIABLE.
Richard M. Stallman's avatar
Richard M. Stallman committed
584
Aliased variables always have the same value; setting one sets the other.
585
Third arg DOCSTRING, if non-nil, is documentation for NEW-ALIAS.  If it is
586 587 588 589
omitted or nil, NEW-ALIAS gets the documentation string of BASE-VARIABLE,
or of the variable at the end of the chain of aliases, if BASE-VARIABLE is
itself an alias.  If NEW-ALIAS is bound, and BASE-VARIABLE is not,
then the value of BASE-VARIABLE is set to that of NEW-ALIAS.
590
The return value is BASE-VARIABLE.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
591
  (Lisp_Object new_alias, Lisp_Object base_variable, Lisp_Object docstring)
Gerd Moellmann's avatar
Gerd Moellmann committed
592 593
{
  struct Lisp_Symbol *sym;
594

595 596
  CHECK_SYMBOL (new_alias);
  CHECK_SYMBOL (base_variable);
Gerd Moellmann's avatar
Gerd Moellmann committed
597

Noam Postavsky's avatar
Noam Postavsky committed
598 599
  if (SYMBOL_CONSTANT_P (new_alias))
    /* Making it an alias effectively changes its value.  */
Stefan Monnier's avatar
Stefan Monnier committed
600
    error ("Cannot make a constant an alias");
601

Noam Postavsky's avatar
Noam Postavsky committed
602 603
  sym = XSYMBOL (new_alias);

604
  switch (sym->u.s.redirect)
605 606 607 608 609
    {
    case SYMBOL_FORWARDED:
      error ("Cannot make an internal variable an alias");
    case SYMBOL_LOCALIZED:
      error ("Don't know how to make a localized variable an alias");
610 611 612 613 614
    case SYMBOL_PLAINVAL:
    case SYMBOL_VARALIAS:
      break;
    default:
      emacs_abort ();
615 616
    }

617
  /* https://lists.gnu.org/r/emacs-devel/2008-04/msg00834.html
618 619 620 621
     If n_a is bound, but b_v is not, set the value of b_v to n_a,
     so that old-code that affects n_a before the aliasing is setup
     still works.  */
  if (NILP (Fboundp (base_variable)))
Noam Postavsky's avatar
Noam Postavsky committed
622 623
    set_internal (base_variable, find_symbol_value (new_alias),
                  Qnil, SET_INTERNAL_BIND);
624 625 626 627
  else if (!NILP (Fboundp (new_alias))
           && !EQ (find_symbol_value (new_alias),
                   find_symbol_value (base_variable)))
    call2 (intern ("display-warning"),
628
           list3 (Qdefvaralias, intern ("losing-value"), new_alias),
629 630 631 632 633
           CALLN (Fformat_message,
                  build_string
                  ("Overwriting value of `%s' by aliasing to `%s'"),
                  new_alias, base_variable));

634
  {
635
    union specbinding *p;
636

Paul Eggert's avatar
Paul Eggert committed
637
    for (p = specpdl_ptr; p > specpdl; )
638 639
      if ((--p)->kind >= SPECPDL_LET
	  && (EQ (new_alias, specpdl_symbol (p))))
640 641 642
	error ("Don't know how to make a let-bound variable an alias");
  }

643
  if (sym->u.s.trapped_write == SYMBOL_TRAPPED_WRITE)
Noam Postavsky's avatar
Noam Postavsky committed
644 645
    notify_variable_watchers (new_alias, base_variable, Qdefvaralias, Qnil);

646 647 648
  sym->u.s.declared_special = true;
  XSYMBOL (base_variable)->u.s.declared_special = true;
  sym->u.s.redirect = SYMBOL_VARALIAS;
649
  SET_SYMBOL_ALIAS (sym, XSYMBOL (base_variable));
650
  sym->u.s.trapped_write = XSYMBOL (base_variable)->u.s.trapped_write;
651
  LOADHIST_ATTACH (new_alias);
652 653
  /* Even if docstring is nil: remove old docstring.  */
  Fput (new_alias, Qvariable_documentation, docstring);
654

655
  return base_variable;
Gerd Moellmann's avatar
Gerd Moellmann committed
656 657
}

658 659 660 661 662 663 664 665 666 667 668 669 670 671
static union specbinding *
default_toplevel_binding (Lisp_Object symbol)
{
  union specbinding *binding = NULL;
  union specbinding *pdl = specpdl_ptr;
  while (pdl > specpdl)
    {
      switch ((--pdl)->kind)
	{
	case SPECPDL_LET_DEFAULT:
	case SPECPDL_LET:
	  if (EQ (specpdl_symbol (pdl), symbol))
	    binding = pdl;
	  break;
672 673

	case SPECPDL_UNWIND:
674
	case SPECPDL_UNWIND_ARRAY:
675 676
	case SPECPDL_UNWIND_PTR:
	case SPECPDL_UNWIND_INT:
677
	case SPECPDL_UNWIND_INTMAX:
678
	case SPECPDL_UNWIND_EXCURSION:
679 680 681 682 683 684 685
	case SPECPDL_UNWIND_VOID:
	case SPECPDL_BACKTRACE:
	case SPECPDL_LET_LOCAL:
	  break;

	default:
	  emacs_abort ();
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
	}
    }
  return binding;
}

DEFUN ("default-toplevel-value", Fdefault_toplevel_value, Sdefault_toplevel_value, 1, 1, 0,
       doc: /* Return SYMBOL's toplevel default value.
"Toplevel" means outside of any let binding.  */)
  (Lisp_Object symbol)
{
  union specbinding *binding = default_toplevel_binding (symbol);
  Lisp_Object value
    = binding ? specpdl_old_value (binding) : Fdefault_value (symbol);
  if (!EQ (value, Qunbound))
    return value;
  xsignal1 (Qvoid_variable, symbol);
}

DEFUN ("set-default-toplevel-value", Fset_default_toplevel_value,
       Sset_default_toplevel_value, 2, 2, 0,
       doc: /* Set SYMBOL's toplevel default value to VALUE.
"Toplevel" means outside of any let binding.  */)
     (Lisp_Object symbol, Lisp_Object value)
{
  union specbinding *binding = default_toplevel_binding (symbol);
  if (binding)
    set_specpdl_old_value (binding, value);
  else
    Fset_default (symbol, value);
  return Qnil;
}
Gerd Moellmann's avatar
Gerd Moellmann committed
717

718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
DEFUN ("internal--define-uninitialized-variable",
       Finternal__define_uninitialized_variable,
       Sinternal__define_uninitialized_variable, 1, 2, 0,
       doc: /* Define SYMBOL as a variable, with DOC as its docstring.
This is like `defvar' and `defconst' but without affecting the variable's
value.  */)
  (Lisp_Object symbol, Lisp_Object doc)
{
  XSYMBOL (symbol)->u.s.declared_special = true;
  if (!NILP (doc))
    {
      if (!NILP (Vpurify_flag))
	doc = Fpurecopy (doc);
      Fput (symbol, Qvariable_documentation, doc);
    }
  LOADHIST_ATTACH (symbol);
  return Qnil;
}

Jim Blandy's avatar
Jim Blandy committed
737
DEFUN ("defvar", Fdefvar, Sdefvar, 1, UNEVALLED, 0,
Juanma Barranquero's avatar
Juanma Barranquero committed
738
       doc: /* Define SYMBOL as a variable, and return SYMBOL.
739 740 741 742 743 744
You are not required to define a variable in order to use it, but
defining it lets you supply an initial value and documentation, which
can be referred to by the Emacs help facilities and other programming
tools.  The `defvar' form also declares the variable as \"special\",
so that it is always dynamically bound even if `lexical-binding' is t.

745 746 747 748 749
If SYMBOL's value is void and the optional argument INITVALUE is
provided, INITVALUE is evaluated and the result used to set SYMBOL's
value.  If SYMBOL is buffer-local, its default value is what is set;
buffer-local values are not affected.  If INITVALUE is missing,
SYMBOL's value is not set.
750 751 752 753 754

If SYMBOL has a local binding, then this form affects the local
binding.  This is usually not what you want.  Thus, if you need to
load a file defining variables, with this form or with `defconst' or
`defcustom', you should always load that file _outside_ any bindings
755
for these variables.  (`defconst' and `defcustom' behave similarly in
756
this respect.)
757 758 759 760 761

The optional argument DOCSTRING is a documentation string for the
variable.

To define a user option, use `defcustom' instead of `defvar'.
762
usage: (defvar SYMBOL &optional INITVALUE DOCSTRING)  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
763
  (Lisp_Object args)
Jim Blandy's avatar
Jim Blandy committed
764
{
765
  Lisp_Object sym, tem, tail;
Jim Blandy's avatar
Jim Blandy committed
766

767 768
  sym = XCAR (args);
  tail = XCDR (args);
769

770 771
  CHECK_SYMBOL (sym);

772
  if (!NILP (tail))
Jim Blandy's avatar
Jim Blandy committed
773
    {
774
      if (!NILP (XCDR (tail)) && !NILP (XCDR (XCDR (tail))))
775
	error ("Too many arguments");
776
      Lisp_Object exp = XCAR (tail);
777 778

      tem = Fdefault_boundp (sym);
779
      tail = XCDR (tail);
780

781
      /* Do it before evaluating the initial value, for self-references.  */
782
      Finternal__define_uninitialized_variable (sym, CAR (tail));
783

Jim Blandy's avatar
Jim Blandy committed
784
      if (NILP (tem))
785
	Fset_default (sym, eval_sub (exp));
786 787 788
      else
	{ /* Check if there is really a global binding rather than just a let
	     binding that shadows the global unboundness of the var.  */
789 790
	  union specbinding *binding = default_toplevel_binding (sym);
	  if (binding && EQ (specpdl_old_value (binding), Qunbound))
791
	    {
792
	      set_specpdl_old_value (binding, eval_sub (exp));
793 794
	    }
	}
Jim Blandy's avatar
Jim Blandy committed
795
    }
796
  else if (!NILP (Vinternal_interpreter_environment)
797
	   && (SYMBOLP (sym) && !XSYMBOL (sym)->u.s.declared_special))
798 799 800
    /* A simple (defvar foo) with lexical scoping does "nothing" except
       declare that var to be dynamically scoped *locally* (i.e. within
       the current file or let-block).  */
801 802
    Vinternal_interpreter_environment
      = Fcons (sym, Vinternal_interpreter_environment);
803
  else
804 805 806 807 808
    {
      /* Simple (defvar <var>) should not count as a definition at all.
	 It could get in the way of other definitions, and unloading this
	 package could try to make the variable unbound.  */
    }
Andreas Schwab's avatar
Andreas Schwab committed
809

Jim Blandy's avatar
Jim Blandy committed
810 811 812 813
  return sym;
}

DEFUN ("defconst", Fdefconst, Sdefconst, 2, UNEVALLED, 0,
Pavel Janík's avatar
Pavel Janík committed
814
       doc: /* Define SYMBOL as a constant variable.
815 816 817 818 819 820 821 822 823 824 825 826 827
This declares that neither programs nor users should ever change the
value.  This constancy is not actually enforced by Emacs Lisp, but
SYMBOL is marked as a special variable so that it is never lexically
bound.

The `defconst' form always sets the value of SYMBOL to the result of
evalling INITVALUE.  If SYMBOL is buffer-local, its default value is
what is set; buffer-local values are not affected.  If SYMBOL has a
local binding, then this form sets the local binding's value.
However, you should normally not make local bindings for variables
defined with this form.

The optional DOCSTRING specifies the variable's documentation string.
828
usage: (defconst SYMBOL INITVALUE [DOCSTRING])  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
829
  (Lisp_Object args)
Jim Blandy's avatar
Jim Blandy committed
830
{
831
  Lisp_Object sym, tem;
Jim Blandy's avatar
Jim Blandy committed
832

833
  sym = XCAR (args);
Stephen Berman's avatar
Stephen Berman committed
834
  CHECK_SYMBOL (sym);
835 836 837 838 839 840 841
  Lisp_Object docstring = Qnil;
  if (!NILP (XCDR (XCDR (args))))
    {
      if (!NILP (XCDR (XCDR (XCDR (args)))))
	error ("Too many arguments");
      docstring = XCAR (XCDR (XCDR (args)));
    }
842

843
  Finternal__define_uninitialized_variable (sym, docstring);
844
  tem = eval_sub (XCAR (XCDR (args)));
845 846
  if (!NILP (Vpurify_flag))
    tem = Fpurecopy (tem);
847 848
  Fset_default (sym, tem);      /* FIXME: set-default-toplevel-value? */
  Fput (sym, Qrisky_local_variable, Qt); /* FIXME: Why?  */
Jim Blandy's avatar
Jim Blandy committed
849 850 851
  return sym;
}

852 853 854 855 856 857 858
/* Make SYMBOL lexically scoped.  */
DEFUN ("internal-make-var-non-special", Fmake_var_non_special,
       Smake_var_non_special, 1, 1, 0,
       doc: /* Internal function.  */)
     (Lisp_Object symbol)
{
  CHECK_SYMBOL (symbol);
859
  XSYMBOL (symbol)->u.s.declared_special = false;
860 861 862
  return Qnil;
}

Jim Blandy's avatar
Jim Blandy committed
863 864

DEFUN ("let*", FletX, SletX, 1, UNEVALLED, 0,
Pavel Janík's avatar
Pavel Janík committed
865 866 867 868 869
       doc: /* Bind variables according to VARLIST then eval BODY.
The value of the last form in BODY is returned.
Each element of VARLIST is a symbol (which is bound to nil)
or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
Each VALUEFORM can refer to the symbols already bound by this VARLIST.
870
usage: (let* VARLIST BODY...)  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
871
  (Lisp_Object args)
Jim Blandy's avatar
Jim Blandy committed
872
{
873
  Lisp_Object var, val, elt, lexenv;
874
  ptrdiff_t count = SPECPDL_INDEX ();
Jim Blandy's avatar
Jim Blandy committed
875

876 877
  lexenv = Vinternal_interpreter_environment;

878 879
  Lisp_Object varlist = XCAR (args);
  while (CONSP (varlist))
Jim Blandy's avatar
Jim Blandy committed
880
    {
Paul Eggert's avatar
Paul Eggert committed
881
      maybe_quit ();
882 883

      elt = XCAR (varlist);
884
      varlist = XCDR (varlist);
885
      if (SYMBOLP (elt))
886 887 888 889
	{
	  var = elt;
	  val = Qnil;
	}
Jim Blandy's avatar
Jim Blandy committed
890 891
      else
	{
892
	  var = Fcar (elt);
893 894 895
	  if (! NILP (Fcdr (XCDR (elt))))
	    signal_error ("`let' bindings can have only one value-form", elt);
	  val = eval_sub (Fcar (XCDR (elt)));
Jim Blandy's avatar
Jim Blandy committed
896
	}
897

898
      if (!NILP (lexenv) && SYMBOLP (var)
899
	  && !XSYMBOL (var)->u.s.declared_special
900
	  && NILP (Fmemq (var, Vinternal_interpreter_environment)))
901 902 903
	/* Lexically bind VAR by adding it to the interpreter's binding
	   alist.  */
	{
904 905 906 907 908 909 910 911 912
	  Lisp_Object newenv
	    = Fcons (Fcons (var, val), Vinternal_interpreter_environment);
	  if (EQ (Vinternal_interpreter_environment, lexenv))
	    /* Save the old lexical environment on the specpdl stack,
	       but only for the first lexical binding, since we'll never
	       need to revert to one of the intermediate ones.  */
	    specbind (Qinternal_interpreter_environment, newenv);
	  else
	    Vinternal_interpreter_environment = newenv;
Jim Blandy's avatar
Jim Blandy committed
913
	}
914 915
      else
	specbind (var, val);
Jim Blandy's avatar
Jim Blandy committed
916
    }
Paul Eggert's avatar
Paul Eggert committed
917
  CHECK_LIST_END (varlist, XCAR (args));
918

919
  val = Fprogn (XCDR (args));
Jim Blandy's avatar
Jim Blandy committed
920 921 922 923
  return unbind_to (count, val);
}

DEFUN ("let", Flet, Slet, 1, UNEVALLED, 0,
Pavel Janík's avatar
Pavel Janík committed
924 925 926 927 928
       doc: /* Bind variables according to VARLIST then eval BODY.
The value of the last form in BODY is returned.
Each element of VARLIST is a symbol (which is bound to nil)
or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
All the VALUEFORMs are evalled before any symbols are bound.
929
usage: (let VARLIST BODY...)  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
930
  (Lisp_Object args)
Jim Blandy's avatar
Jim Blandy committed
931
{
932
  Lisp_Object *temps, tem, lexenv;
Paul Eggert's avatar
Paul Eggert committed
933
  Lisp_Object elt;
934
  ptrdiff_t count = SPECPDL_INDEX ();
935
  ptrdiff_t argnum;
936
  USE_SAFE_ALLOCA;
Jim Blandy's avatar
Jim Blandy committed
937

Paul Eggert's avatar
Paul Eggert committed
938
  Lisp_Object varlist = XCAR (args);
Jim Blandy's avatar
Jim Blandy committed
939

940
  /* Make space to hold the values to give the bound variables.  */
Paul Eggert's avatar
Paul Eggert committed
941
  EMACS_INT varlist_len = list_length (varlist);
942 943
  SAFE_ALLOCA_LISP (temps, varlist_len);
  ptrdiff_t nvars = varlist_len;
Jim Blandy's avatar
Jim Blandy committed
944

945
  /* Compute the values and store them in `temps'.  */
Jim Blandy's avatar
Jim Blandy committed
946

947
  for (argnum = 0; argnum < nvars && CONSP (varlist); argnum++)
Jim Blandy's avatar
Jim Blandy committed
948
    {
Paul Eggert's avatar
Paul Eggert committed
949
      maybe_quit ();
950
      elt = XCAR (varlist);
951
      varlist = XCDR (varlist);
952
      if (SYMBOLP (elt))
953
	temps[argnum] = Qnil;
Jim Blandy's avatar
Jim Blandy committed
954
      else if (! NILP (Fcdr (Fcdr (elt))))
955
	signal_error ("`let' bindings can have only one value-form", elt);
Jim Blandy's avatar
Jim Blandy committed
956
      else
957
	temps[argnum] = eval_sub (Fcar (Fcdr (elt)));
Jim Blandy's avatar
Jim Blandy committed
958
    }
959
  nvars = argnum;
Jim Blandy's avatar
Jim Blandy committed
960

961 962
  lexenv = Vinternal_interpreter_environment;

963
  varlist = XCAR (args);
964
  for (argnum = 0; argnum < nvars && CONSP (varlist); argnum++)
Jim Blandy's avatar
Jim Blandy committed
965
    {
966 967
      Lisp_Object var;

968
      elt = XCAR (varlist);
969
      varlist = XCDR (varlist);
970
      var = SYMBOLP (elt) ? elt : Fcar (elt);
971
      tem = temps[argnum];
972

973
      if (!NILP (lexenv) && SYMBOLP (var)
974
	  && !XSYMBOL (var)->u.s.declared_special
975
	  && NILP (Fmemq (var, Vinternal_interpreter_environment)))
976 977
	/* Lexically bind VAR by adding it to the lexenv alist.  */
	lexenv = Fcons (Fcons (var, tem), lexenv);
Jim Blandy's avatar
Jim Blandy committed
978
      else
979 980
	/* Dynamically bind VAR.  */
	specbind (var, tem);
Jim Blandy's avatar
Jim Blandy committed
981