* lisp/simple.el (read-expression-map): Use completion-at-point.
[bpt/emacs.git] / src / lread.c
1 /* Lisp parsing and input streams.
2
3 Copyright (C) 1985-1989, 1993-1995, 1997-2013 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 <stdio.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <sys/file.h>
27 #include <errno.h>
28 #include <limits.h> /* For CHAR_BIT. */
29 #include <stat-time.h>
30 #include "lisp.h"
31 #include "intervals.h"
32 #include "character.h"
33 #include "buffer.h"
34 #include "charset.h"
35 #include "coding.h"
36 #include <epaths.h>
37 #include "commands.h"
38 #include "keyboard.h"
39 #include "frame.h"
40 #include "termhooks.h"
41 #include "coding.h"
42 #include "blockinput.h"
43
44 #ifdef MSDOS
45 #include "msdos.h"
46 #endif
47
48 #ifdef HAVE_NS
49 #include "nsterm.h"
50 #endif
51
52 #include <unistd.h>
53
54 #ifdef HAVE_SETLOCALE
55 #include <locale.h>
56 #endif /* HAVE_SETLOCALE */
57
58 #include <fcntl.h>
59
60 #ifdef HAVE_FSEEKO
61 #define file_offset off_t
62 #define file_tell ftello
63 #else
64 #define file_offset long
65 #define file_tell ftell
66 #endif
67
68 /* Hash table read constants. */
69 static Lisp_Object Qhash_table, Qdata;
70 static Lisp_Object Qtest, Qsize;
71 static Lisp_Object Qweakness;
72 static Lisp_Object Qrehash_size;
73 static Lisp_Object Qrehash_threshold;
74
75 static Lisp_Object Qread_char, Qget_file_char, Qcurrent_load_list;
76 Lisp_Object Qstandard_input;
77 Lisp_Object Qvariable_documentation;
78 static Lisp_Object Qascii_character, Qload, Qload_file_name;
79 Lisp_Object Qbackquote, Qcomma, Qcomma_at, Qcomma_dot, Qfunction;
80 static Lisp_Object Qinhibit_file_name_operation;
81 static Lisp_Object Qeval_buffer_list;
82 Lisp_Object Qlexical_binding;
83 static Lisp_Object Qfile_truename, Qdo_after_load_evaluation; /* ACM 2006/5/16 */
84
85 /* Used instead of Qget_file_char while loading *.elc files compiled
86 by Emacs 21 or older. */
87 static Lisp_Object Qget_emacs_mule_file_char;
88
89 static Lisp_Object Qload_force_doc_strings;
90
91 static Lisp_Object Qload_in_progress;
92
93 /* The association list of objects read with the #n=object form.
94 Each member of the list has the form (n . object), and is used to
95 look up the object for the corresponding #n# construct.
96 It must be set to nil before all top-level calls to read0. */
97 static Lisp_Object read_objects;
98
99 /* List of descriptors now open for Fload. */
100 static Lisp_Object load_descriptor_list;
101
102 /* File for get_file_char to read from. Use by load. */
103 static FILE *instream;
104
105 /* For use within read-from-string (this reader is non-reentrant!!) */
106 static ptrdiff_t read_from_string_index;
107 static ptrdiff_t read_from_string_index_byte;
108 static ptrdiff_t read_from_string_limit;
109
110 /* Number of characters read in the current call to Fread or
111 Fread_from_string. */
112 static EMACS_INT readchar_count;
113
114 /* This contains the last string skipped with #@. */
115 static char *saved_doc_string;
116 /* Length of buffer allocated in saved_doc_string. */
117 static ptrdiff_t saved_doc_string_size;
118 /* Length of actual data in saved_doc_string. */
119 static ptrdiff_t saved_doc_string_length;
120 /* This is the file position that string came from. */
121 static file_offset saved_doc_string_position;
122
123 /* This contains the previous string skipped with #@.
124 We copy it from saved_doc_string when a new string
125 is put in saved_doc_string. */
126 static char *prev_saved_doc_string;
127 /* Length of buffer allocated in prev_saved_doc_string. */
128 static ptrdiff_t prev_saved_doc_string_size;
129 /* Length of actual data in prev_saved_doc_string. */
130 static ptrdiff_t prev_saved_doc_string_length;
131 /* This is the file position that string came from. */
132 static file_offset prev_saved_doc_string_position;
133
134 /* True means inside a new-style backquote
135 with no surrounding parentheses.
136 Fread initializes this to false, so we need not specbind it
137 or worry about what happens to it when there is an error. */
138 static bool new_backquote_flag;
139 static Lisp_Object Qold_style_backquotes;
140
141 /* A list of file names for files being loaded in Fload. Used to
142 check for recursive loads. */
143
144 static Lisp_Object Vloads_in_progress;
145
146 static int read_emacs_mule_char (int, int (*) (int, Lisp_Object),
147 Lisp_Object);
148
149 static void readevalloop (Lisp_Object, FILE *, Lisp_Object, bool,
150 Lisp_Object, Lisp_Object,
151 Lisp_Object, Lisp_Object);
152 static Lisp_Object load_unwind (Lisp_Object);
153 static Lisp_Object load_descriptor_unwind (Lisp_Object);
154 \f
155 /* Functions that read one byte from the current source READCHARFUN
156 or unreads one byte. If the integer argument C is -1, it returns
157 one read byte, or -1 when there's no more byte in the source. If C
158 is 0 or positive, it unreads C, and the return value is not
159 interesting. */
160
161 static int readbyte_for_lambda (int, Lisp_Object);
162 static int readbyte_from_file (int, Lisp_Object);
163 static int readbyte_from_string (int, Lisp_Object);
164
165 /* Handle unreading and rereading of characters.
166 Write READCHAR to read a character,
167 UNREAD(c) to unread c to be read again.
168
169 These macros correctly read/unread multibyte characters. */
170
171 #define READCHAR readchar (readcharfun, NULL)
172 #define UNREAD(c) unreadchar (readcharfun, c)
173
174 /* Same as READCHAR but set *MULTIBYTE to the multibyteness of the source. */
175 #define READCHAR_REPORT_MULTIBYTE(multibyte) readchar (readcharfun, multibyte)
176
177 /* When READCHARFUN is Qget_file_char, Qget_emacs_mule_file_char,
178 Qlambda, or a cons, we use this to keep an unread character because
179 a file stream can't handle multibyte-char unreading. The value -1
180 means that there's no unread character. */
181 static int unread_char;
182
183 static int
184 readchar (Lisp_Object readcharfun, bool *multibyte)
185 {
186 Lisp_Object tem;
187 register int c;
188 int (*readbyte) (int, Lisp_Object);
189 unsigned char buf[MAX_MULTIBYTE_LENGTH];
190 int i, len;
191 bool emacs_mule_encoding = 0;
192
193 if (multibyte)
194 *multibyte = 0;
195
196 readchar_count++;
197
198 if (BUFFERP (readcharfun))
199 {
200 register struct buffer *inbuffer = XBUFFER (readcharfun);
201
202 ptrdiff_t pt_byte = BUF_PT_BYTE (inbuffer);
203
204 if (pt_byte >= BUF_ZV_BYTE (inbuffer))
205 return -1;
206
207 if (! NILP (BVAR (inbuffer, enable_multibyte_characters)))
208 {
209 /* Fetch the character code from the buffer. */
210 unsigned char *p = BUF_BYTE_ADDRESS (inbuffer, pt_byte);
211 BUF_INC_POS (inbuffer, pt_byte);
212 c = STRING_CHAR (p);
213 if (multibyte)
214 *multibyte = 1;
215 }
216 else
217 {
218 c = BUF_FETCH_BYTE (inbuffer, pt_byte);
219 if (! ASCII_BYTE_P (c))
220 c = BYTE8_TO_CHAR (c);
221 pt_byte++;
222 }
223 SET_BUF_PT_BOTH (inbuffer, BUF_PT (inbuffer) + 1, pt_byte);
224
225 return c;
226 }
227 if (MARKERP (readcharfun))
228 {
229 register struct buffer *inbuffer = XMARKER (readcharfun)->buffer;
230
231 ptrdiff_t bytepos = marker_byte_position (readcharfun);
232
233 if (bytepos >= BUF_ZV_BYTE (inbuffer))
234 return -1;
235
236 if (! NILP (BVAR (inbuffer, enable_multibyte_characters)))
237 {
238 /* Fetch the character code from the buffer. */
239 unsigned char *p = BUF_BYTE_ADDRESS (inbuffer, bytepos);
240 BUF_INC_POS (inbuffer, bytepos);
241 c = STRING_CHAR (p);
242 if (multibyte)
243 *multibyte = 1;
244 }
245 else
246 {
247 c = BUF_FETCH_BYTE (inbuffer, bytepos);
248 if (! ASCII_BYTE_P (c))
249 c = BYTE8_TO_CHAR (c);
250 bytepos++;
251 }
252
253 XMARKER (readcharfun)->bytepos = bytepos;
254 XMARKER (readcharfun)->charpos++;
255
256 return c;
257 }
258
259 if (EQ (readcharfun, Qlambda))
260 {
261 readbyte = readbyte_for_lambda;
262 goto read_multibyte;
263 }
264
265 if (EQ (readcharfun, Qget_file_char))
266 {
267 readbyte = readbyte_from_file;
268 goto read_multibyte;
269 }
270
271 if (STRINGP (readcharfun))
272 {
273 if (read_from_string_index >= read_from_string_limit)
274 c = -1;
275 else if (STRING_MULTIBYTE (readcharfun))
276 {
277 if (multibyte)
278 *multibyte = 1;
279 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, readcharfun,
280 read_from_string_index,
281 read_from_string_index_byte);
282 }
283 else
284 {
285 c = SREF (readcharfun, read_from_string_index_byte);
286 read_from_string_index++;
287 read_from_string_index_byte++;
288 }
289 return c;
290 }
291
292 if (CONSP (readcharfun))
293 {
294 /* This is the case that read_vector is reading from a unibyte
295 string that contains a byte sequence previously skipped
296 because of #@NUMBER. The car part of readcharfun is that
297 string, and the cdr part is a value of readcharfun given to
298 read_vector. */
299 readbyte = readbyte_from_string;
300 if (EQ (XCDR (readcharfun), Qget_emacs_mule_file_char))
301 emacs_mule_encoding = 1;
302 goto read_multibyte;
303 }
304
305 if (EQ (readcharfun, Qget_emacs_mule_file_char))
306 {
307 readbyte = readbyte_from_file;
308 emacs_mule_encoding = 1;
309 goto read_multibyte;
310 }
311
312 tem = call0 (readcharfun);
313
314 if (NILP (tem))
315 return -1;
316 return XINT (tem);
317
318 read_multibyte:
319 if (unread_char >= 0)
320 {
321 c = unread_char;
322 unread_char = -1;
323 return c;
324 }
325 c = (*readbyte) (-1, readcharfun);
326 if (c < 0)
327 return c;
328 if (multibyte)
329 *multibyte = 1;
330 if (ASCII_BYTE_P (c))
331 return c;
332 if (emacs_mule_encoding)
333 return read_emacs_mule_char (c, readbyte, readcharfun);
334 i = 0;
335 buf[i++] = c;
336 len = BYTES_BY_CHAR_HEAD (c);
337 while (i < len)
338 {
339 c = (*readbyte) (-1, readcharfun);
340 if (c < 0 || ! TRAILING_CODE_P (c))
341 {
342 while (--i > 1)
343 (*readbyte) (buf[i], readcharfun);
344 return BYTE8_TO_CHAR (buf[0]);
345 }
346 buf[i++] = c;
347 }
348 return STRING_CHAR (buf);
349 }
350
351 #define FROM_FILE_P(readcharfun) \
352 (EQ (readcharfun, Qget_file_char) \
353 || EQ (readcharfun, Qget_emacs_mule_file_char))
354
355 static void
356 skip_dyn_bytes (Lisp_Object readcharfun, ptrdiff_t n)
357 {
358 if (FROM_FILE_P (readcharfun))
359 {
360 block_input (); /* FIXME: Not sure if it's needed. */
361 fseek (instream, n, SEEK_CUR);
362 unblock_input ();
363 }
364 else
365 { /* We're not reading directly from a file. In that case, it's difficult
366 to reliably count bytes, since these are usually meant for the file's
367 encoding, whereas we're now typically in the internal encoding.
368 But luckily, skip_dyn_bytes is used to skip over a single
369 dynamic-docstring (or dynamic byte-code) which is always quoted such
370 that \037 is the final char. */
371 int c;
372 do {
373 c = READCHAR;
374 } while (c >= 0 && c != '\037');
375 }
376 }
377
378 /* Unread the character C in the way appropriate for the stream READCHARFUN.
379 If the stream is a user function, call it with the char as argument. */
380
381 static void
382 unreadchar (Lisp_Object readcharfun, int c)
383 {
384 readchar_count--;
385 if (c == -1)
386 /* Don't back up the pointer if we're unreading the end-of-input mark,
387 since readchar didn't advance it when we read it. */
388 ;
389 else if (BUFFERP (readcharfun))
390 {
391 struct buffer *b = XBUFFER (readcharfun);
392 ptrdiff_t charpos = BUF_PT (b);
393 ptrdiff_t bytepos = BUF_PT_BYTE (b);
394
395 if (! NILP (BVAR (b, enable_multibyte_characters)))
396 BUF_DEC_POS (b, bytepos);
397 else
398 bytepos--;
399
400 SET_BUF_PT_BOTH (b, charpos - 1, bytepos);
401 }
402 else if (MARKERP (readcharfun))
403 {
404 struct buffer *b = XMARKER (readcharfun)->buffer;
405 ptrdiff_t bytepos = XMARKER (readcharfun)->bytepos;
406
407 XMARKER (readcharfun)->charpos--;
408 if (! NILP (BVAR (b, enable_multibyte_characters)))
409 BUF_DEC_POS (b, bytepos);
410 else
411 bytepos--;
412
413 XMARKER (readcharfun)->bytepos = bytepos;
414 }
415 else if (STRINGP (readcharfun))
416 {
417 read_from_string_index--;
418 read_from_string_index_byte
419 = string_char_to_byte (readcharfun, read_from_string_index);
420 }
421 else if (CONSP (readcharfun))
422 {
423 unread_char = c;
424 }
425 else if (EQ (readcharfun, Qlambda))
426 {
427 unread_char = c;
428 }
429 else if (FROM_FILE_P (readcharfun))
430 {
431 unread_char = c;
432 }
433 else
434 call1 (readcharfun, make_number (c));
435 }
436
437 static int
438 readbyte_for_lambda (int c, Lisp_Object readcharfun)
439 {
440 return read_bytecode_char (c >= 0);
441 }
442
443
444 static int
445 readbyte_from_file (int c, Lisp_Object readcharfun)
446 {
447 if (c >= 0)
448 {
449 block_input ();
450 ungetc (c, instream);
451 unblock_input ();
452 return 0;
453 }
454
455 block_input ();
456 c = getc (instream);
457
458 /* Interrupted reads have been observed while reading over the network. */
459 while (c == EOF && ferror (instream) && errno == EINTR)
460 {
461 unblock_input ();
462 QUIT;
463 block_input ();
464 clearerr (instream);
465 c = getc (instream);
466 }
467
468 unblock_input ();
469
470 return (c == EOF ? -1 : c);
471 }
472
473 static int
474 readbyte_from_string (int c, Lisp_Object readcharfun)
475 {
476 Lisp_Object string = XCAR (readcharfun);
477
478 if (c >= 0)
479 {
480 read_from_string_index--;
481 read_from_string_index_byte
482 = string_char_to_byte (string, read_from_string_index);
483 }
484
485 if (read_from_string_index >= read_from_string_limit)
486 c = -1;
487 else
488 FETCH_STRING_CHAR_ADVANCE (c, string,
489 read_from_string_index,
490 read_from_string_index_byte);
491 return c;
492 }
493
494
495 /* Read one non-ASCII character from INSTREAM. The character is
496 encoded in `emacs-mule' and the first byte is already read in
497 C. */
498
499 static int
500 read_emacs_mule_char (int c, int (*readbyte) (int, Lisp_Object), Lisp_Object readcharfun)
501 {
502 /* Emacs-mule coding uses at most 4-byte for one character. */
503 unsigned char buf[4];
504 int len = emacs_mule_bytes[c];
505 struct charset *charset;
506 int i;
507 unsigned code;
508
509 if (len == 1)
510 /* C is not a valid leading-code of `emacs-mule'. */
511 return BYTE8_TO_CHAR (c);
512
513 i = 0;
514 buf[i++] = c;
515 while (i < len)
516 {
517 c = (*readbyte) (-1, readcharfun);
518 if (c < 0xA0)
519 {
520 while (--i > 1)
521 (*readbyte) (buf[i], readcharfun);
522 return BYTE8_TO_CHAR (buf[0]);
523 }
524 buf[i++] = c;
525 }
526
527 if (len == 2)
528 {
529 charset = CHARSET_FROM_ID (emacs_mule_charset[buf[0]]);
530 code = buf[1] & 0x7F;
531 }
532 else if (len == 3)
533 {
534 if (buf[0] == EMACS_MULE_LEADING_CODE_PRIVATE_11
535 || buf[0] == EMACS_MULE_LEADING_CODE_PRIVATE_12)
536 {
537 charset = CHARSET_FROM_ID (emacs_mule_charset[buf[1]]);
538 code = buf[2] & 0x7F;
539 }
540 else
541 {
542 charset = CHARSET_FROM_ID (emacs_mule_charset[buf[0]]);
543 code = ((buf[1] << 8) | buf[2]) & 0x7F7F;
544 }
545 }
546 else
547 {
548 charset = CHARSET_FROM_ID (emacs_mule_charset[buf[1]]);
549 code = ((buf[2] << 8) | buf[3]) & 0x7F7F;
550 }
551 c = DECODE_CHAR (charset, code);
552 if (c < 0)
553 Fsignal (Qinvalid_read_syntax,
554 Fcons (build_string ("invalid multibyte form"), Qnil));
555 return c;
556 }
557
558
559 static Lisp_Object read_internal_start (Lisp_Object, Lisp_Object,
560 Lisp_Object);
561 static Lisp_Object read0 (Lisp_Object);
562 static Lisp_Object read1 (Lisp_Object, int *, bool);
563
564 static Lisp_Object read_list (bool, Lisp_Object);
565 static Lisp_Object read_vector (Lisp_Object, bool);
566
567 static Lisp_Object substitute_object_recurse (Lisp_Object, Lisp_Object,
568 Lisp_Object);
569 static void substitute_object_in_subtree (Lisp_Object,
570 Lisp_Object);
571 static void substitute_in_interval (INTERVAL, Lisp_Object);
572
573 \f
574 /* Get a character from the tty. */
575
576 /* Read input events until we get one that's acceptable for our purposes.
577
578 If NO_SWITCH_FRAME, switch-frame events are stashed
579 until we get a character we like, and then stuffed into
580 unread_switch_frame.
581
582 If ASCII_REQUIRED, check function key events to see
583 if the unmodified version of the symbol has a Qascii_character
584 property, and use that character, if present.
585
586 If ERROR_NONASCII, signal an error if the input we
587 get isn't an ASCII character with modifiers. If it's false but
588 ASCII_REQUIRED is true, just re-read until we get an ASCII
589 character.
590
591 If INPUT_METHOD, invoke the current input method
592 if the character warrants that.
593
594 If SECONDS is a number, wait that many seconds for input, and
595 return Qnil if no input arrives within that time. */
596
597 static Lisp_Object
598 read_filtered_event (bool no_switch_frame, bool ascii_required,
599 bool error_nonascii, bool input_method, Lisp_Object seconds)
600 {
601 Lisp_Object val, delayed_switch_frame;
602 EMACS_TIME end_time;
603
604 #ifdef HAVE_WINDOW_SYSTEM
605 if (display_hourglass_p)
606 cancel_hourglass ();
607 #endif
608
609 delayed_switch_frame = Qnil;
610
611 /* Compute timeout. */
612 if (NUMBERP (seconds))
613 {
614 double duration = extract_float (seconds);
615 EMACS_TIME wait_time = EMACS_TIME_FROM_DOUBLE (duration);
616 end_time = add_emacs_time (current_emacs_time (), wait_time);
617 }
618
619 /* Read until we get an acceptable event. */
620 retry:
621 do
622 val = read_char (0, Qnil, (input_method ? Qnil : Qt), 0,
623 NUMBERP (seconds) ? &end_time : NULL);
624 while (INTEGERP (val) && XINT (val) == -2); /* wrong_kboard_jmpbuf */
625
626 if (BUFFERP (val))
627 goto retry;
628
629 /* `switch-frame' events are put off until after the next ASCII
630 character. This is better than signaling an error just because
631 the last characters were typed to a separate minibuffer frame,
632 for example. Eventually, some code which can deal with
633 switch-frame events will read it and process it. */
634 if (no_switch_frame
635 && EVENT_HAS_PARAMETERS (val)
636 && EQ (EVENT_HEAD_KIND (EVENT_HEAD (val)), Qswitch_frame))
637 {
638 delayed_switch_frame = val;
639 goto retry;
640 }
641
642 if (ascii_required && !(NUMBERP (seconds) && NILP (val)))
643 {
644 /* Convert certain symbols to their ASCII equivalents. */
645 if (SYMBOLP (val))
646 {
647 Lisp_Object tem, tem1;
648 tem = Fget (val, Qevent_symbol_element_mask);
649 if (!NILP (tem))
650 {
651 tem1 = Fget (Fcar (tem), Qascii_character);
652 /* Merge this symbol's modifier bits
653 with the ASCII equivalent of its basic code. */
654 if (!NILP (tem1))
655 XSETFASTINT (val, XINT (tem1) | XINT (Fcar (Fcdr (tem))));
656 }
657 }
658
659 /* If we don't have a character now, deal with it appropriately. */
660 if (!INTEGERP (val))
661 {
662 if (error_nonascii)
663 {
664 Vunread_command_events = Fcons (val, Qnil);
665 error ("Non-character input-event");
666 }
667 else
668 goto retry;
669 }
670 }
671
672 if (! NILP (delayed_switch_frame))
673 unread_switch_frame = delayed_switch_frame;
674
675 #if 0
676
677 #ifdef HAVE_WINDOW_SYSTEM
678 if (display_hourglass_p)
679 start_hourglass ();
680 #endif
681
682 #endif
683
684 return val;
685 }
686
687 DEFUN ("read-char", Fread_char, Sread_char, 0, 3, 0,
688 doc: /* Read a character from the command input (keyboard or macro).
689 It is returned as a number.
690 If the character has modifiers, they are resolved and reflected to the
691 character code if possible (e.g. C-SPC -> 0).
692
693 If the user generates an event which is not a character (i.e. a mouse
694 click or function key event), `read-char' signals an error. As an
695 exception, switch-frame events are put off until non-character events
696 can be read.
697 If you want to read non-character events, or ignore them, call
698 `read-event' or `read-char-exclusive' instead.
699
700 If the optional argument PROMPT is non-nil, display that as a prompt.
701 If the optional argument INHERIT-INPUT-METHOD is non-nil and some
702 input method is turned on in the current buffer, that input method
703 is used for reading a character.
704 If the optional argument SECONDS is non-nil, it should be a number
705 specifying the maximum number of seconds to wait for input. If no
706 input arrives in that time, return nil. SECONDS may be a
707 floating-point value. */)
708 (Lisp_Object prompt, Lisp_Object inherit_input_method, Lisp_Object seconds)
709 {
710 Lisp_Object val;
711
712 if (! NILP (prompt))
713 message_with_string ("%s", prompt, 0);
714 val = read_filtered_event (1, 1, 1, ! NILP (inherit_input_method), seconds);
715
716 return (NILP (val) ? Qnil
717 : make_number (char_resolve_modifier_mask (XINT (val))));
718 }
719
720 DEFUN ("read-event", Fread_event, Sread_event, 0, 3, 0,
721 doc: /* Read an event object from the input stream.
722 If the optional argument PROMPT is non-nil, display that as a prompt.
723 If the optional argument INHERIT-INPUT-METHOD is non-nil and some
724 input method is turned on in the current buffer, that input method
725 is used for reading a character.
726 If the optional argument SECONDS is non-nil, it should be a number
727 specifying the maximum number of seconds to wait for input. If no
728 input arrives in that time, return nil. SECONDS may be a
729 floating-point value. */)
730 (Lisp_Object prompt, Lisp_Object inherit_input_method, Lisp_Object seconds)
731 {
732 if (! NILP (prompt))
733 message_with_string ("%s", prompt, 0);
734 return read_filtered_event (0, 0, 0, ! NILP (inherit_input_method), seconds);
735 }
736
737 DEFUN ("read-char-exclusive", Fread_char_exclusive, Sread_char_exclusive, 0, 3, 0,
738 doc: /* Read a character from the command input (keyboard or macro).
739 It is returned as a number. Non-character events are ignored.
740 If the character has modifiers, they are resolved and reflected to the
741 character code if possible (e.g. C-SPC -> 0).
742
743 If the optional argument PROMPT is non-nil, display that as a prompt.
744 If the optional argument INHERIT-INPUT-METHOD is non-nil and some
745 input method is turned on in the current buffer, that input method
746 is used for reading a character.
747 If the optional argument SECONDS is non-nil, it should be a number
748 specifying the maximum number of seconds to wait for input. If no
749 input arrives in that time, return nil. SECONDS may be a
750 floating-point value. */)
751 (Lisp_Object prompt, Lisp_Object inherit_input_method, Lisp_Object seconds)
752 {
753 Lisp_Object val;
754
755 if (! NILP (prompt))
756 message_with_string ("%s", prompt, 0);
757
758 val = read_filtered_event (1, 1, 0, ! NILP (inherit_input_method), seconds);
759
760 return (NILP (val) ? Qnil
761 : make_number (char_resolve_modifier_mask (XINT (val))));
762 }
763
764 DEFUN ("get-file-char", Fget_file_char, Sget_file_char, 0, 0, 0,
765 doc: /* Don't use this yourself. */)
766 (void)
767 {
768 register Lisp_Object val;
769 block_input ();
770 XSETINT (val, getc (instream));
771 unblock_input ();
772 return val;
773 }
774
775
776 \f
777
778 /* Return true if the lisp code read using READCHARFUN defines a non-nil
779 `lexical-binding' file variable. After returning, the stream is
780 positioned following the first line, if it is a comment or #! line,
781 otherwise nothing is read. */
782
783 static bool
784 lisp_file_lexically_bound_p (Lisp_Object readcharfun)
785 {
786 int ch = READCHAR;
787
788 if (ch == '#')
789 {
790 ch = READCHAR;
791 if (ch != '!')
792 {
793 UNREAD (ch);
794 UNREAD ('#');
795 return 0;
796 }
797 while (ch != '\n' && ch != EOF)
798 ch = READCHAR;
799 if (ch == '\n') ch = READCHAR;
800 /* It is OK to leave the position after a #! line, since
801 that is what read1 does. */
802 }
803
804 if (ch != ';')
805 /* The first line isn't a comment, just give up. */
806 {
807 UNREAD (ch);
808 return 0;
809 }
810 else
811 /* Look for an appropriate file-variable in the first line. */
812 {
813 bool rv = 0;
814 enum {
815 NOMINAL, AFTER_FIRST_DASH, AFTER_ASTERIX,
816 } beg_end_state = NOMINAL;
817 bool in_file_vars = 0;
818
819 #define UPDATE_BEG_END_STATE(ch) \
820 if (beg_end_state == NOMINAL) \
821 beg_end_state = (ch == '-' ? AFTER_FIRST_DASH : NOMINAL); \
822 else if (beg_end_state == AFTER_FIRST_DASH) \
823 beg_end_state = (ch == '*' ? AFTER_ASTERIX : NOMINAL); \
824 else if (beg_end_state == AFTER_ASTERIX) \
825 { \
826 if (ch == '-') \
827 in_file_vars = !in_file_vars; \
828 beg_end_state = NOMINAL; \
829 }
830
831 /* Skip until we get to the file vars, if any. */
832 do
833 {
834 ch = READCHAR;
835 UPDATE_BEG_END_STATE (ch);
836 }
837 while (!in_file_vars && ch != '\n' && ch != EOF);
838
839 while (in_file_vars)
840 {
841 char var[100], val[100];
842 unsigned i;
843
844 ch = READCHAR;
845
846 /* Read a variable name. */
847 while (ch == ' ' || ch == '\t')
848 ch = READCHAR;
849
850 i = 0;
851 while (ch != ':' && ch != '\n' && ch != EOF && in_file_vars)
852 {
853 if (i < sizeof var - 1)
854 var[i++] = ch;
855 UPDATE_BEG_END_STATE (ch);
856 ch = READCHAR;
857 }
858
859 /* Stop scanning if no colon was found before end marker. */
860 if (!in_file_vars || ch == '\n' || ch == EOF)
861 break;
862
863 while (i > 0 && (var[i - 1] == ' ' || var[i - 1] == '\t'))
864 i--;
865 var[i] = '\0';
866
867 if (ch == ':')
868 {
869 /* Read a variable value. */
870 ch = READCHAR;
871
872 while (ch == ' ' || ch == '\t')
873 ch = READCHAR;
874
875 i = 0;
876 while (ch != ';' && ch != '\n' && ch != EOF && in_file_vars)
877 {
878 if (i < sizeof val - 1)
879 val[i++] = ch;
880 UPDATE_BEG_END_STATE (ch);
881 ch = READCHAR;
882 }
883 if (! in_file_vars)
884 /* The value was terminated by an end-marker, which remove. */
885 i -= 3;
886 while (i > 0 && (val[i - 1] == ' ' || val[i - 1] == '\t'))
887 i--;
888 val[i] = '\0';
889
890 if (strcmp (var, "lexical-binding") == 0)
891 /* This is it... */
892 {
893 rv = (strcmp (val, "nil") != 0);
894 break;
895 }
896 }
897 }
898
899 while (ch != '\n' && ch != EOF)
900 ch = READCHAR;
901
902 return rv;
903 }
904 }
905 \f
906 /* Value is a version number of byte compiled code if the file
907 associated with file descriptor FD is a compiled Lisp file that's
908 safe to load. Only files compiled with Emacs are safe to load.
909 Files compiled with XEmacs can lead to a crash in Fbyte_code
910 because of an incompatible change in the byte compiler. */
911
912 static int
913 safe_to_load_version (int fd)
914 {
915 char buf[512];
916 int nbytes, i;
917 int version = 1;
918
919 /* Read the first few bytes from the file, and look for a line
920 specifying the byte compiler version used. */
921 nbytes = emacs_read (fd, buf, sizeof buf);
922 if (nbytes > 0)
923 {
924 /* Skip to the next newline, skipping over the initial `ELC'
925 with NUL bytes following it, but note the version. */
926 for (i = 0; i < nbytes && buf[i] != '\n'; ++i)
927 if (i == 4)
928 version = buf[i];
929
930 if (i >= nbytes
931 || fast_c_string_match_ignore_case (Vbytecomp_version_regexp,
932 buf + i, nbytes - i) < 0)
933 version = 0;
934 }
935
936 lseek (fd, 0, SEEK_SET);
937 return version;
938 }
939
940
941 /* Callback for record_unwind_protect. Restore the old load list OLD,
942 after loading a file successfully. */
943
944 static Lisp_Object
945 record_load_unwind (Lisp_Object old)
946 {
947 return Vloads_in_progress = old;
948 }
949
950 /* This handler function is used via internal_condition_case_1. */
951
952 static Lisp_Object
953 load_error_handler (Lisp_Object data)
954 {
955 return Qnil;
956 }
957
958 static Lisp_Object
959 load_warn_old_style_backquotes (Lisp_Object file)
960 {
961 if (!NILP (Vold_style_backquotes))
962 {
963 Lisp_Object args[2];
964 args[0] = build_string ("Loading `%s': old-style backquotes detected!");
965 args[1] = file;
966 Fmessage (2, args);
967 }
968 return Qnil;
969 }
970
971 DEFUN ("get-load-suffixes", Fget_load_suffixes, Sget_load_suffixes, 0, 0, 0,
972 doc: /* Return the suffixes that `load' should try if a suffix is \
973 required.
974 This uses the variables `load-suffixes' and `load-file-rep-suffixes'. */)
975 (void)
976 {
977 Lisp_Object lst = Qnil, suffixes = Vload_suffixes, suffix, ext;
978 while (CONSP (suffixes))
979 {
980 Lisp_Object exts = Vload_file_rep_suffixes;
981 suffix = XCAR (suffixes);
982 suffixes = XCDR (suffixes);
983 while (CONSP (exts))
984 {
985 ext = XCAR (exts);
986 exts = XCDR (exts);
987 lst = Fcons (concat2 (suffix, ext), lst);
988 }
989 }
990 return Fnreverse (lst);
991 }
992
993 DEFUN ("load", Fload, Sload, 1, 5, 0,
994 doc: /* Execute a file of Lisp code named FILE.
995 First try FILE with `.elc' appended, then try with `.el',
996 then try FILE unmodified (the exact suffixes in the exact order are
997 determined by `load-suffixes'). Environment variable references in
998 FILE are replaced with their values by calling `substitute-in-file-name'.
999 This function searches the directories in `load-path'.
1000
1001 If optional second arg NOERROR is non-nil,
1002 report no error if FILE doesn't exist.
1003 Print messages at start and end of loading unless
1004 optional third arg NOMESSAGE is non-nil (but `force-load-messages'
1005 overrides that).
1006 If optional fourth arg NOSUFFIX is non-nil, don't try adding
1007 suffixes `.elc' or `.el' to the specified name FILE.
1008 If optional fifth arg MUST-SUFFIX is non-nil, insist on
1009 the suffix `.elc' or `.el'; don't accept just FILE unless
1010 it ends in one of those suffixes or includes a directory name.
1011
1012 If NOSUFFIX is nil, then if a file could not be found, try looking for
1013 a different representation of the file by adding non-empty suffixes to
1014 its name, before trying another file. Emacs uses this feature to find
1015 compressed versions of files when Auto Compression mode is enabled.
1016 If NOSUFFIX is non-nil, disable this feature.
1017
1018 The suffixes that this function tries out, when NOSUFFIX is nil, are
1019 given by the return value of `get-load-suffixes' and the values listed
1020 in `load-file-rep-suffixes'. If MUST-SUFFIX is non-nil, only the
1021 return value of `get-load-suffixes' is used, i.e. the file name is
1022 required to have a non-empty suffix.
1023
1024 Loading a file records its definitions, and its `provide' and
1025 `require' calls, in an element of `load-history' whose
1026 car is the file name loaded. See `load-history'.
1027
1028 While the file is in the process of being loaded, the variable
1029 `load-in-progress' is non-nil and the variable `load-file-name'
1030 is bound to the file's name.
1031
1032 Return t if the file exists and loads successfully. */)
1033 (Lisp_Object file, Lisp_Object noerror, Lisp_Object nomessage, Lisp_Object nosuffix, Lisp_Object must_suffix)
1034 {
1035 register FILE *stream;
1036 register int fd = -1;
1037 ptrdiff_t count = SPECPDL_INDEX ();
1038 struct gcpro gcpro1, gcpro2, gcpro3;
1039 Lisp_Object found, efound, hist_file_name;
1040 /* True means we printed the ".el is newer" message. */
1041 bool newer = 0;
1042 /* True means we are loading a compiled file. */
1043 bool compiled = 0;
1044 Lisp_Object handler;
1045 bool safe_p = 1;
1046 const char *fmode = "r";
1047 Lisp_Object tmp[2];
1048 int version;
1049
1050 #ifdef DOS_NT
1051 fmode = "rt";
1052 #endif /* DOS_NT */
1053
1054 CHECK_STRING (file);
1055
1056 /* If file name is magic, call the handler. */
1057 /* This shouldn't be necessary any more now that `openp' handles it right.
1058 handler = Ffind_file_name_handler (file, Qload);
1059 if (!NILP (handler))
1060 return call5 (handler, Qload, file, noerror, nomessage, nosuffix); */
1061
1062 /* Do this after the handler to avoid
1063 the need to gcpro noerror, nomessage and nosuffix.
1064 (Below here, we care only whether they are nil or not.)
1065 The presence of this call is the result of a historical accident:
1066 it used to be in every file-operation and when it got removed
1067 everywhere, it accidentally stayed here. Since then, enough people
1068 supposedly have things like (load "$PROJECT/foo.el") in their .emacs
1069 that it seemed risky to remove. */
1070 if (! NILP (noerror))
1071 {
1072 file = internal_condition_case_1 (Fsubstitute_in_file_name, file,
1073 Qt, load_error_handler);
1074 if (NILP (file))
1075 return Qnil;
1076 }
1077 else
1078 file = Fsubstitute_in_file_name (file);
1079
1080
1081 /* Avoid weird lossage with null string as arg,
1082 since it would try to load a directory as a Lisp file. */
1083 if (SBYTES (file) > 0)
1084 {
1085 ptrdiff_t size = SBYTES (file);
1086
1087 found = Qnil;
1088 GCPRO2 (file, found);
1089
1090 if (! NILP (must_suffix))
1091 {
1092 /* Don't insist on adding a suffix if FILE already ends with one. */
1093 if (size > 3
1094 && !strcmp (SSDATA (file) + size - 3, ".el"))
1095 must_suffix = Qnil;
1096 else if (size > 4
1097 && !strcmp (SSDATA (file) + size - 4, ".elc"))
1098 must_suffix = Qnil;
1099 /* Don't insist on adding a suffix
1100 if the argument includes a directory name. */
1101 else if (! NILP (Ffile_name_directory (file)))
1102 must_suffix = Qnil;
1103 }
1104
1105 fd = openp (Vload_path, file,
1106 (!NILP (nosuffix) ? Qnil
1107 : !NILP (must_suffix) ? Fget_load_suffixes ()
1108 : Fappend (2, (tmp[0] = Fget_load_suffixes (),
1109 tmp[1] = Vload_file_rep_suffixes,
1110 tmp))),
1111 &found, Qnil);
1112 UNGCPRO;
1113 }
1114
1115 if (fd == -1)
1116 {
1117 if (NILP (noerror))
1118 xsignal2 (Qfile_error, build_string ("Cannot open load file"), file);
1119 return Qnil;
1120 }
1121
1122 /* Tell startup.el whether or not we found the user's init file. */
1123 if (EQ (Qt, Vuser_init_file))
1124 Vuser_init_file = found;
1125
1126 /* If FD is -2, that means openp found a magic file. */
1127 if (fd == -2)
1128 {
1129 if (NILP (Fequal (found, file)))
1130 /* If FOUND is a different file name from FILE,
1131 find its handler even if we have already inhibited
1132 the `load' operation on FILE. */
1133 handler = Ffind_file_name_handler (found, Qt);
1134 else
1135 handler = Ffind_file_name_handler (found, Qload);
1136 if (! NILP (handler))
1137 return call5 (handler, Qload, found, noerror, nomessage, Qt);
1138 #ifdef DOS_NT
1139 /* Tramp has to deal with semi-broken packages that prepend
1140 drive letters to remote files. For that reason, Tramp
1141 catches file operations that test for file existence, which
1142 makes openp think X:/foo.elc files are remote. However,
1143 Tramp does not catch `load' operations for such files, so we
1144 end up with a nil as the `load' handler above. If we would
1145 continue with fd = -2, we will behave wrongly, and in
1146 particular try reading a .elc file in the "rt" mode instead
1147 of "rb". See bug #9311 for the results. To work around
1148 this, we try to open the file locally, and go with that if it
1149 succeeds. */
1150 fd = emacs_open (SSDATA (ENCODE_FILE (found)), O_RDONLY, 0);
1151 if (fd == -1)
1152 fd = -2;
1153 #endif
1154 }
1155
1156 /* Check if we're stuck in a recursive load cycle.
1157
1158 2000-09-21: It's not possible to just check for the file loaded
1159 being a member of Vloads_in_progress. This fails because of the
1160 way the byte compiler currently works; `provide's are not
1161 evaluated, see font-lock.el/jit-lock.el as an example. This
1162 leads to a certain amount of ``normal'' recursion.
1163
1164 Also, just loading a file recursively is not always an error in
1165 the general case; the second load may do something different. */
1166 {
1167 int load_count = 0;
1168 Lisp_Object tem;
1169 for (tem = Vloads_in_progress; CONSP (tem); tem = XCDR (tem))
1170 if (!NILP (Fequal (found, XCAR (tem))) && (++load_count > 3))
1171 {
1172 if (fd >= 0)
1173 emacs_close (fd);
1174 signal_error ("Recursive load", Fcons (found, Vloads_in_progress));
1175 }
1176 record_unwind_protect (record_load_unwind, Vloads_in_progress);
1177 Vloads_in_progress = Fcons (found, Vloads_in_progress);
1178 }
1179
1180 /* All loads are by default dynamic, unless the file itself specifies
1181 otherwise using a file-variable in the first line. This is bound here
1182 so that it takes effect whether or not we use
1183 Vload_source_file_function. */
1184 specbind (Qlexical_binding, Qnil);
1185
1186 /* Get the name for load-history. */
1187 hist_file_name = (! NILP (Vpurify_flag)
1188 ? Fconcat (2, (tmp[0] = Ffile_name_directory (file),
1189 tmp[1] = Ffile_name_nondirectory (found),
1190 tmp))
1191 : found) ;
1192
1193 version = -1;
1194
1195 /* Check for the presence of old-style quotes and warn about them. */
1196 specbind (Qold_style_backquotes, Qnil);
1197 record_unwind_protect (load_warn_old_style_backquotes, file);
1198
1199 if (!memcmp (SDATA (found) + SBYTES (found) - 4, ".elc", 4)
1200 || (fd >= 0 && (version = safe_to_load_version (fd)) > 0))
1201 /* Load .elc files directly, but not when they are
1202 remote and have no handler! */
1203 {
1204 if (fd != -2)
1205 {
1206 struct stat s1, s2;
1207 int result;
1208
1209 GCPRO3 (file, found, hist_file_name);
1210
1211 if (version < 0
1212 && ! (version = safe_to_load_version (fd)))
1213 {
1214 safe_p = 0;
1215 if (!load_dangerous_libraries)
1216 {
1217 if (fd >= 0)
1218 emacs_close (fd);
1219 error ("File `%s' was not compiled in Emacs",
1220 SDATA (found));
1221 }
1222 else if (!NILP (nomessage) && !force_load_messages)
1223 message_with_string ("File `%s' not compiled in Emacs", found, 1);
1224 }
1225
1226 compiled = 1;
1227
1228 efound = ENCODE_FILE (found);
1229
1230 #ifdef DOS_NT
1231 fmode = "rb";
1232 #endif /* DOS_NT */
1233 result = stat (SSDATA (efound), &s1);
1234 if (result == 0)
1235 {
1236 SSET (efound, SBYTES (efound) - 1, 0);
1237 result = stat (SSDATA (efound), &s2);
1238 SSET (efound, SBYTES (efound) - 1, 'c');
1239 }
1240
1241 if (result == 0
1242 && EMACS_TIME_LT (get_stat_mtime (&s1), get_stat_mtime (&s2)))
1243 {
1244 /* Make the progress messages mention that source is newer. */
1245 newer = 1;
1246
1247 /* If we won't print another message, mention this anyway. */
1248 if (!NILP (nomessage) && !force_load_messages)
1249 {
1250 Lisp_Object msg_file;
1251 msg_file = Fsubstring (found, make_number (0), make_number (-1));
1252 message_with_string ("Source file `%s' newer than byte-compiled file",
1253 msg_file, 1);
1254 }
1255 }
1256 UNGCPRO;
1257 }
1258 }
1259 else
1260 {
1261 /* We are loading a source file (*.el). */
1262 if (!NILP (Vload_source_file_function))
1263 {
1264 Lisp_Object val;
1265
1266 if (fd >= 0)
1267 emacs_close (fd);
1268 val = call4 (Vload_source_file_function, found, hist_file_name,
1269 NILP (noerror) ? Qnil : Qt,
1270 (NILP (nomessage) || force_load_messages) ? Qnil : Qt);
1271 return unbind_to (count, val);
1272 }
1273 }
1274
1275 GCPRO3 (file, found, hist_file_name);
1276
1277 #ifdef WINDOWSNT
1278 efound = ENCODE_FILE (found);
1279 /* If we somehow got here with fd == -2, meaning the file is deemed
1280 to be remote, don't even try to reopen the file locally; just
1281 force a failure instead. */
1282 if (fd >= 0)
1283 {
1284 emacs_close (fd);
1285 stream = fopen (SSDATA (efound), fmode);
1286 }
1287 else
1288 stream = NULL;
1289 #else /* not WINDOWSNT */
1290 stream = fdopen (fd, fmode);
1291 #endif /* not WINDOWSNT */
1292 if (stream == 0)
1293 {
1294 emacs_close (fd);
1295 error ("Failure to create stdio stream for %s", SDATA (file));
1296 }
1297
1298 if (! NILP (Vpurify_flag))
1299 Vpreloaded_file_list = Fcons (Fpurecopy (file), Vpreloaded_file_list);
1300
1301 if (NILP (nomessage) || force_load_messages)
1302 {
1303 if (!safe_p)
1304 message_with_string ("Loading %s (compiled; note unsafe, not compiled in Emacs)...",
1305 file, 1);
1306 else if (!compiled)
1307 message_with_string ("Loading %s (source)...", file, 1);
1308 else if (newer)
1309 message_with_string ("Loading %s (compiled; note, source file is newer)...",
1310 file, 1);
1311 else /* The typical case; compiled file newer than source file. */
1312 message_with_string ("Loading %s...", file, 1);
1313 }
1314
1315 record_unwind_protect (load_unwind, make_save_pointer (stream));
1316 record_unwind_protect (load_descriptor_unwind, load_descriptor_list);
1317 specbind (Qload_file_name, found);
1318 specbind (Qinhibit_file_name_operation, Qnil);
1319 load_descriptor_list
1320 = Fcons (make_number (fileno (stream)), load_descriptor_list);
1321 specbind (Qload_in_progress, Qt);
1322
1323 instream = stream;
1324 if (lisp_file_lexically_bound_p (Qget_file_char))
1325 Fset (Qlexical_binding, Qt);
1326
1327 if (! version || version >= 22)
1328 readevalloop (Qget_file_char, stream, hist_file_name,
1329 0, Qnil, Qnil, Qnil, Qnil);
1330 else
1331 {
1332 /* We can't handle a file which was compiled with
1333 byte-compile-dynamic by older version of Emacs. */
1334 specbind (Qload_force_doc_strings, Qt);
1335 readevalloop (Qget_emacs_mule_file_char, stream, hist_file_name,
1336 0, Qnil, Qnil, Qnil, Qnil);
1337 }
1338 unbind_to (count, Qnil);
1339
1340 /* Run any eval-after-load forms for this file. */
1341 if (!NILP (Ffboundp (Qdo_after_load_evaluation)))
1342 call1 (Qdo_after_load_evaluation, hist_file_name) ;
1343
1344 UNGCPRO;
1345
1346 xfree (saved_doc_string);
1347 saved_doc_string = 0;
1348 saved_doc_string_size = 0;
1349
1350 xfree (prev_saved_doc_string);
1351 prev_saved_doc_string = 0;
1352 prev_saved_doc_string_size = 0;
1353
1354 if (!noninteractive && (NILP (nomessage) || force_load_messages))
1355 {
1356 if (!safe_p)
1357 message_with_string ("Loading %s (compiled; note unsafe, not compiled in Emacs)...done",
1358 file, 1);
1359 else if (!compiled)
1360 message_with_string ("Loading %s (source)...done", file, 1);
1361 else if (newer)
1362 message_with_string ("Loading %s (compiled; note, source file is newer)...done",
1363 file, 1);
1364 else /* The typical case; compiled file newer than source file. */
1365 message_with_string ("Loading %s...done", file, 1);
1366 }
1367
1368 return Qt;
1369 }
1370
1371 static Lisp_Object
1372 load_unwind (Lisp_Object arg) /* Used as unwind-protect function in load. */
1373 {
1374 FILE *stream = XSAVE_POINTER (arg, 0);
1375 if (stream != NULL)
1376 {
1377 block_input ();
1378 fclose (stream);
1379 unblock_input ();
1380 }
1381 return Qnil;
1382 }
1383
1384 static Lisp_Object
1385 load_descriptor_unwind (Lisp_Object oldlist)
1386 {
1387 load_descriptor_list = oldlist;
1388 return Qnil;
1389 }
1390
1391 /* Close all descriptors in use for Floads.
1392 This is used when starting a subprocess. */
1393
1394 void
1395 close_load_descs (void)
1396 {
1397 #ifndef WINDOWSNT
1398 Lisp_Object tail;
1399 for (tail = load_descriptor_list; CONSP (tail); tail = XCDR (tail))
1400 emacs_close (XFASTINT (XCAR (tail)));
1401 #endif
1402 }
1403 \f
1404 static bool
1405 complete_filename_p (Lisp_Object pathname)
1406 {
1407 const unsigned char *s = SDATA (pathname);
1408 return (IS_DIRECTORY_SEP (s[0])
1409 || (SCHARS (pathname) > 2
1410 && IS_DEVICE_SEP (s[1]) && IS_DIRECTORY_SEP (s[2])));
1411 }
1412
1413 DEFUN ("locate-file-internal", Flocate_file_internal, Slocate_file_internal, 2, 4, 0,
1414 doc: /* Search for FILENAME through PATH.
1415 Returns the file's name in absolute form, or nil if not found.
1416 If SUFFIXES is non-nil, it should be a list of suffixes to append to
1417 file name when searching.
1418 If non-nil, PREDICATE is used instead of `file-readable-p'.
1419 PREDICATE can also be an integer to pass to the faccessat(2) function,
1420 in which case file-name-handlers are ignored.
1421 This function will normally skip directories, so if you want it to find
1422 directories, make sure the PREDICATE function returns `dir-ok' for them. */)
1423 (Lisp_Object filename, Lisp_Object path, Lisp_Object suffixes, Lisp_Object predicate)
1424 {
1425 Lisp_Object file;
1426 int fd = openp (path, filename, suffixes, &file, predicate);
1427 if (NILP (predicate) && fd > 0)
1428 close (fd);
1429 return file;
1430 }
1431
1432 static Lisp_Object Qdir_ok;
1433
1434 /* Search for a file whose name is STR, looking in directories
1435 in the Lisp list PATH, and trying suffixes from SUFFIX.
1436 On success, returns a file descriptor. On failure, returns -1.
1437
1438 SUFFIXES is a list of strings containing possible suffixes.
1439 The empty suffix is automatically added if the list is empty.
1440
1441 PREDICATE non-nil means don't open the files,
1442 just look for one that satisfies the predicate. In this case,
1443 returns 1 on success. The predicate can be a lisp function or
1444 an integer to pass to `access' (in which case file-name-handlers
1445 are ignored).
1446
1447 If STOREPTR is nonzero, it points to a slot where the name of
1448 the file actually found should be stored as a Lisp string.
1449 nil is stored there on failure.
1450
1451 If the file we find is remote, return -2
1452 but store the found remote file name in *STOREPTR. */
1453
1454 int
1455 openp (Lisp_Object path, Lisp_Object str, Lisp_Object suffixes, Lisp_Object *storeptr, Lisp_Object predicate)
1456 {
1457 ptrdiff_t fn_size = 100;
1458 char buf[100];
1459 char *fn = buf;
1460 bool absolute = 0;
1461 ptrdiff_t want_length;
1462 Lisp_Object filename;
1463 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
1464 Lisp_Object string, tail, encoded_fn;
1465 ptrdiff_t max_suffix_len = 0;
1466
1467 CHECK_STRING (str);
1468
1469 for (tail = suffixes; CONSP (tail); tail = XCDR (tail))
1470 {
1471 CHECK_STRING_CAR (tail);
1472 max_suffix_len = max (max_suffix_len,
1473 SBYTES (XCAR (tail)));
1474 }
1475
1476 string = filename = encoded_fn = Qnil;
1477 GCPRO6 (str, string, filename, path, suffixes, encoded_fn);
1478
1479 if (storeptr)
1480 *storeptr = Qnil;
1481
1482 if (complete_filename_p (str))
1483 absolute = 1;
1484
1485 for (; CONSP (path); path = XCDR (path))
1486 {
1487 filename = Fexpand_file_name (str, XCAR (path));
1488 if (!complete_filename_p (filename))
1489 /* If there are non-absolute elts in PATH (eg "."). */
1490 /* Of course, this could conceivably lose if luser sets
1491 default-directory to be something non-absolute... */
1492 {
1493 filename = Fexpand_file_name (filename, BVAR (current_buffer, directory));
1494 if (!complete_filename_p (filename))
1495 /* Give up on this path element! */
1496 continue;
1497 }
1498
1499 /* Calculate maximum length of any filename made from
1500 this path element/specified file name and any possible suffix. */
1501 want_length = max_suffix_len + SBYTES (filename);
1502 if (fn_size <= want_length)
1503 fn = alloca (fn_size = 100 + want_length);
1504
1505 /* Loop over suffixes. */
1506 for (tail = NILP (suffixes) ? Fcons (empty_unibyte_string, Qnil) : suffixes;
1507 CONSP (tail); tail = XCDR (tail))
1508 {
1509 ptrdiff_t fnlen, lsuffix = SBYTES (XCAR (tail));
1510 Lisp_Object handler;
1511
1512 /* Concatenate path element/specified name with the suffix.
1513 If the directory starts with /:, remove that. */
1514 int prefixlen = ((SCHARS (filename) > 2
1515 && SREF (filename, 0) == '/'
1516 && SREF (filename, 1) == ':')
1517 ? 2 : 0);
1518 fnlen = SBYTES (filename) - prefixlen;
1519 memcpy (fn, SDATA (filename) + prefixlen, fnlen);
1520 memcpy (fn + fnlen, SDATA (XCAR (tail)), lsuffix + 1);
1521 fnlen += lsuffix;
1522 /* Check that the file exists and is not a directory. */
1523 /* We used to only check for handlers on non-absolute file names:
1524 if (absolute)
1525 handler = Qnil;
1526 else
1527 handler = Ffind_file_name_handler (filename, Qfile_exists_p);
1528 It's not clear why that was the case and it breaks things like
1529 (load "/bar.el") where the file is actually "/bar.el.gz". */
1530 string = make_string (fn, fnlen);
1531 handler = Ffind_file_name_handler (string, Qfile_exists_p);
1532 if ((!NILP (handler) || !NILP (predicate)) && !NATNUMP (predicate))
1533 {
1534 bool exists;
1535 if (NILP (predicate))
1536 exists = !NILP (Ffile_readable_p (string));
1537 else
1538 {
1539 Lisp_Object tmp = call1 (predicate, string);
1540 exists = !NILP (tmp)
1541 && (EQ (tmp, Qdir_ok)
1542 || NILP (Ffile_directory_p (string)));
1543 }
1544
1545 if (exists)
1546 {
1547 /* We succeeded; return this descriptor and filename. */
1548 if (storeptr)
1549 *storeptr = string;
1550 UNGCPRO;
1551 return -2;
1552 }
1553 }
1554 else
1555 {
1556 int fd;
1557 const char *pfn;
1558
1559 encoded_fn = ENCODE_FILE (string);
1560 pfn = SSDATA (encoded_fn);
1561
1562 /* Check that we can access or open it. */
1563 if (NATNUMP (predicate))
1564 fd = (((XFASTINT (predicate) & ~INT_MAX) == 0
1565 && (faccessat (AT_FDCWD, pfn, XFASTINT (predicate),
1566 AT_EACCESS)
1567 == 0)
1568 && ! file_directory_p (pfn))
1569 ? 1 : -1);
1570 else
1571 {
1572 struct stat st;
1573 fd = emacs_open (pfn, O_RDONLY, 0);
1574 if (fd >= 0
1575 && (fstat (fd, &st) != 0 || S_ISDIR (st.st_mode)))
1576 {
1577 emacs_close (fd);
1578 fd = -1;
1579 }
1580 }
1581
1582 if (fd >= 0)
1583 {
1584 /* We succeeded; return this descriptor and filename. */
1585 if (storeptr)
1586 *storeptr = string;
1587 UNGCPRO;
1588 return fd;
1589 }
1590 }
1591 }
1592 if (absolute)
1593 break;
1594 }
1595
1596 UNGCPRO;
1597 return -1;
1598 }
1599
1600 \f
1601 /* Merge the list we've accumulated of globals from the current input source
1602 into the load_history variable. The details depend on whether
1603 the source has an associated file name or not.
1604
1605 FILENAME is the file name that we are loading from.
1606
1607 ENTIRE is true if loading that entire file, false if evaluating
1608 part of it. */
1609
1610 static void
1611 build_load_history (Lisp_Object filename, bool entire)
1612 {
1613 Lisp_Object tail, prev, newelt;
1614 Lisp_Object tem, tem2;
1615 bool foundit = 0;
1616
1617 tail = Vload_history;
1618 prev = Qnil;
1619
1620 while (CONSP (tail))
1621 {
1622 tem = XCAR (tail);
1623
1624 /* Find the feature's previous assoc list... */
1625 if (!NILP (Fequal (filename, Fcar (tem))))
1626 {
1627 foundit = 1;
1628
1629 /* If we're loading the entire file, remove old data. */
1630 if (entire)
1631 {
1632 if (NILP (prev))
1633 Vload_history = XCDR (tail);
1634 else
1635 Fsetcdr (prev, XCDR (tail));
1636 }
1637
1638 /* Otherwise, cons on new symbols that are not already members. */
1639 else
1640 {
1641 tem2 = Vcurrent_load_list;
1642
1643 while (CONSP (tem2))
1644 {
1645 newelt = XCAR (tem2);
1646
1647 if (NILP (Fmember (newelt, tem)))
1648 Fsetcar (tail, Fcons (XCAR (tem),
1649 Fcons (newelt, XCDR (tem))));
1650
1651 tem2 = XCDR (tem2);
1652 QUIT;
1653 }
1654 }
1655 }
1656 else
1657 prev = tail;
1658 tail = XCDR (tail);
1659 QUIT;
1660 }
1661
1662 /* If we're loading an entire file, cons the new assoc onto the
1663 front of load-history, the most-recently-loaded position. Also
1664 do this if we didn't find an existing member for the file. */
1665 if (entire || !foundit)
1666 Vload_history = Fcons (Fnreverse (Vcurrent_load_list),
1667 Vload_history);
1668 }
1669
1670 static Lisp_Object
1671 readevalloop_1 (Lisp_Object old)
1672 {
1673 load_convert_to_unibyte = ! NILP (old);
1674 return Qnil;
1675 }
1676
1677 /* Signal an `end-of-file' error, if possible with file name
1678 information. */
1679
1680 static _Noreturn void
1681 end_of_file_error (void)
1682 {
1683 if (STRINGP (Vload_file_name))
1684 xsignal1 (Qend_of_file, Vload_file_name);
1685
1686 xsignal0 (Qend_of_file);
1687 }
1688
1689 /* UNIBYTE specifies how to set load_convert_to_unibyte
1690 for this invocation.
1691 READFUN, if non-nil, is used instead of `read'.
1692
1693 START, END specify region to read in current buffer (from eval-region).
1694 If the input is not from a buffer, they must be nil. */
1695
1696 static void
1697 readevalloop (Lisp_Object readcharfun,
1698 FILE *stream,
1699 Lisp_Object sourcename,
1700 bool printflag,
1701 Lisp_Object unibyte, Lisp_Object readfun,
1702 Lisp_Object start, Lisp_Object end)
1703 {
1704 register int c;
1705 register Lisp_Object val;
1706 ptrdiff_t count = SPECPDL_INDEX ();
1707 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1708 struct buffer *b = 0;
1709 bool continue_reading_p;
1710 Lisp_Object lex_bound;
1711 /* True if reading an entire buffer. */
1712 bool whole_buffer = 0;
1713 /* True on the first time around. */
1714 bool first_sexp = 1;
1715 Lisp_Object macroexpand = intern ("internal-macroexpand-for-load");
1716
1717 if (NILP (Ffboundp (macroexpand))
1718 /* Don't macroexpand in .elc files, since it should have been done
1719 already. We actually don't know whether we're in a .elc file or not,
1720 so we use circumstantial evidence: .el files normally go through
1721 Vload_source_file_function -> load-with-code-conversion
1722 -> eval-buffer. */
1723 || EQ (readcharfun, Qget_file_char)
1724 || EQ (readcharfun, Qget_emacs_mule_file_char))
1725 macroexpand = Qnil;
1726
1727 if (MARKERP (readcharfun))
1728 {
1729 if (NILP (start))
1730 start = readcharfun;
1731 }
1732
1733 if (BUFFERP (readcharfun))
1734 b = XBUFFER (readcharfun);
1735 else if (MARKERP (readcharfun))
1736 b = XMARKER (readcharfun)->buffer;
1737
1738 /* We assume START is nil when input is not from a buffer. */
1739 if (! NILP (start) && !b)
1740 emacs_abort ();
1741
1742 specbind (Qstandard_input, readcharfun); /* GCPROs readcharfun. */
1743 specbind (Qcurrent_load_list, Qnil);
1744 record_unwind_protect (readevalloop_1, load_convert_to_unibyte ? Qt : Qnil);
1745 load_convert_to_unibyte = !NILP (unibyte);
1746
1747 /* If lexical binding is active (either because it was specified in
1748 the file's header, or via a buffer-local variable), create an empty
1749 lexical environment, otherwise, turn off lexical binding. */
1750 lex_bound = find_symbol_value (Qlexical_binding);
1751 specbind (Qinternal_interpreter_environment,
1752 NILP (lex_bound) || EQ (lex_bound, Qunbound)
1753 ? Qnil : Fcons (Qt, Qnil));
1754
1755 GCPRO4 (sourcename, readfun, start, end);
1756
1757 /* Try to ensure sourcename is a truename, except whilst preloading. */
1758 if (NILP (Vpurify_flag)
1759 && !NILP (sourcename) && !NILP (Ffile_name_absolute_p (sourcename))
1760 && !NILP (Ffboundp (Qfile_truename)))
1761 sourcename = call1 (Qfile_truename, sourcename) ;
1762
1763 LOADHIST_ATTACH (sourcename);
1764
1765 continue_reading_p = 1;
1766 while (continue_reading_p)
1767 {
1768 ptrdiff_t count1 = SPECPDL_INDEX ();
1769
1770 if (b != 0 && !BUFFER_LIVE_P (b))
1771 error ("Reading from killed buffer");
1772
1773 if (!NILP (start))
1774 {
1775 /* Switch to the buffer we are reading from. */
1776 record_unwind_protect (save_excursion_restore, save_excursion_save ());
1777 set_buffer_internal (b);
1778
1779 /* Save point in it. */
1780 record_unwind_protect (save_excursion_restore, save_excursion_save ());
1781 /* Save ZV in it. */
1782 record_unwind_protect (save_restriction_restore, save_restriction_save ());
1783 /* Those get unbound after we read one expression. */
1784
1785 /* Set point and ZV around stuff to be read. */
1786 Fgoto_char (start);
1787 if (!NILP (end))
1788 Fnarrow_to_region (make_number (BEGV), end);
1789
1790 /* Just for cleanliness, convert END to a marker
1791 if it is an integer. */
1792 if (INTEGERP (end))
1793 end = Fpoint_max_marker ();
1794 }
1795
1796 /* On the first cycle, we can easily test here
1797 whether we are reading the whole buffer. */
1798 if (b && first_sexp)
1799 whole_buffer = (PT == BEG && ZV == Z);
1800
1801 instream = stream;
1802 read_next:
1803 c = READCHAR;
1804 if (c == ';')
1805 {
1806 while ((c = READCHAR) != '\n' && c != -1);
1807 goto read_next;
1808 }
1809 if (c < 0)
1810 {
1811 unbind_to (count1, Qnil);
1812 break;
1813 }
1814
1815 /* Ignore whitespace here, so we can detect eof. */
1816 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\r'
1817 || c == 0xa0) /* NBSP */
1818 goto read_next;
1819
1820 if (!NILP (Vpurify_flag) && c == '(')
1821 {
1822 val = read_list (0, readcharfun);
1823 }
1824 else
1825 {
1826 UNREAD (c);
1827 read_objects = Qnil;
1828 if (!NILP (readfun))
1829 {
1830 val = call1 (readfun, readcharfun);
1831
1832 /* If READCHARFUN has set point to ZV, we should
1833 stop reading, even if the form read sets point
1834 to a different value when evaluated. */
1835 if (BUFFERP (readcharfun))
1836 {
1837 struct buffer *buf = XBUFFER (readcharfun);
1838 if (BUF_PT (buf) == BUF_ZV (buf))
1839 continue_reading_p = 0;
1840 }
1841 }
1842 else if (! NILP (Vload_read_function))
1843 val = call1 (Vload_read_function, readcharfun);
1844 else
1845 val = read_internal_start (readcharfun, Qnil, Qnil);
1846 }
1847
1848 if (!NILP (start) && continue_reading_p)
1849 start = Fpoint_marker ();
1850
1851 /* Restore saved point and BEGV. */
1852 unbind_to (count1, Qnil);
1853
1854 /* Now eval what we just read. */
1855 if (!NILP (macroexpand))
1856 val = call1 (macroexpand, val);
1857 val = eval_sub (val);
1858
1859 if (printflag)
1860 {
1861 Vvalues = Fcons (val, Vvalues);
1862 if (EQ (Vstandard_output, Qt))
1863 Fprin1 (val, Qnil);
1864 else
1865 Fprint (val, Qnil);
1866 }
1867
1868 first_sexp = 0;
1869 }
1870
1871 build_load_history (sourcename,
1872 stream || whole_buffer);
1873
1874 UNGCPRO;
1875
1876 unbind_to (count, Qnil);
1877 }
1878
1879 DEFUN ("eval-buffer", Feval_buffer, Seval_buffer, 0, 5, "",
1880 doc: /* Execute the current buffer as Lisp code.
1881 When called from a Lisp program (i.e., not interactively), this
1882 function accepts up to five optional arguments:
1883 BUFFER is the buffer to evaluate (nil means use current buffer).
1884 PRINTFLAG controls printing of output:
1885 A value of nil means discard it; anything else is stream for print.
1886 FILENAME specifies the file name to use for `load-history'.
1887 UNIBYTE, if non-nil, specifies `load-convert-to-unibyte' for this
1888 invocation.
1889 DO-ALLOW-PRINT, if non-nil, specifies that `print' and related
1890 functions should work normally even if PRINTFLAG is nil.
1891
1892 This function preserves the position of point. */)
1893 (Lisp_Object buffer, Lisp_Object printflag, Lisp_Object filename, Lisp_Object unibyte, Lisp_Object do_allow_print)
1894 {
1895 ptrdiff_t count = SPECPDL_INDEX ();
1896 Lisp_Object tem, buf;
1897
1898 if (NILP (buffer))
1899 buf = Fcurrent_buffer ();
1900 else
1901 buf = Fget_buffer (buffer);
1902 if (NILP (buf))
1903 error ("No such buffer");
1904
1905 if (NILP (printflag) && NILP (do_allow_print))
1906 tem = Qsymbolp;
1907 else
1908 tem = printflag;
1909
1910 if (NILP (filename))
1911 filename = BVAR (XBUFFER (buf), filename);
1912
1913 specbind (Qeval_buffer_list, Fcons (buf, Veval_buffer_list));
1914 specbind (Qstandard_output, tem);
1915 record_unwind_protect (save_excursion_restore, save_excursion_save ());
1916 BUF_TEMP_SET_PT (XBUFFER (buf), BUF_BEGV (XBUFFER (buf)));
1917 specbind (Qlexical_binding, lisp_file_lexically_bound_p (buf) ? Qt : Qnil);
1918 readevalloop (buf, 0, filename,
1919 !NILP (printflag), unibyte, Qnil, Qnil, Qnil);
1920 unbind_to (count, Qnil);
1921
1922 return Qnil;
1923 }
1924
1925 DEFUN ("eval-region", Feval_region, Seval_region, 2, 4, "r",
1926 doc: /* Execute the region as Lisp code.
1927 When called from programs, expects two arguments,
1928 giving starting and ending indices in the current buffer
1929 of the text to be executed.
1930 Programs can pass third argument PRINTFLAG which controls output:
1931 A value of nil means discard it; anything else is stream for printing it.
1932 Also the fourth argument READ-FUNCTION, if non-nil, is used
1933 instead of `read' to read each expression. It gets one argument
1934 which is the input stream for reading characters.
1935
1936 This function does not move point. */)
1937 (Lisp_Object start, Lisp_Object end, Lisp_Object printflag, Lisp_Object read_function)
1938 {
1939 /* FIXME: Do the eval-sexp-add-defvars dance! */
1940 ptrdiff_t count = SPECPDL_INDEX ();
1941 Lisp_Object tem, cbuf;
1942
1943 cbuf = Fcurrent_buffer ();
1944
1945 if (NILP (printflag))
1946 tem = Qsymbolp;
1947 else
1948 tem = printflag;
1949 specbind (Qstandard_output, tem);
1950 specbind (Qeval_buffer_list, Fcons (cbuf, Veval_buffer_list));
1951
1952 /* `readevalloop' calls functions which check the type of start and end. */
1953 readevalloop (cbuf, 0, BVAR (XBUFFER (cbuf), filename),
1954 !NILP (printflag), Qnil, read_function,
1955 start, end);
1956
1957 return unbind_to (count, Qnil);
1958 }
1959
1960 \f
1961 DEFUN ("read", Fread, Sread, 0, 1, 0,
1962 doc: /* Read one Lisp expression as text from STREAM, return as Lisp object.
1963 If STREAM is nil, use the value of `standard-input' (which see).
1964 STREAM or the value of `standard-input' may be:
1965 a buffer (read from point and advance it)
1966 a marker (read from where it points and advance it)
1967 a function (call it with no arguments for each character,
1968 call it with a char as argument to push a char back)
1969 a string (takes text from string, starting at the beginning)
1970 t (read text line using minibuffer and use it, or read from
1971 standard input in batch mode). */)
1972 (Lisp_Object stream)
1973 {
1974 if (NILP (stream))
1975 stream = Vstandard_input;
1976 if (EQ (stream, Qt))
1977 stream = Qread_char;
1978 if (EQ (stream, Qread_char))
1979 /* FIXME: ¿¡ When is this used !? */
1980 return call1 (intern ("read-minibuffer"),
1981 build_string ("Lisp expression: "));
1982
1983 return read_internal_start (stream, Qnil, Qnil);
1984 }
1985
1986 DEFUN ("read-from-string", Fread_from_string, Sread_from_string, 1, 3, 0,
1987 doc: /* Read one Lisp expression which is represented as text by STRING.
1988 Returns a cons: (OBJECT-READ . FINAL-STRING-INDEX).
1989 FINAL-STRING-INDEX is an integer giving the position of the next
1990 remaining character in STRING.
1991 START and END optionally delimit a substring of STRING from which to read;
1992 they default to 0 and (length STRING) respectively. */)
1993 (Lisp_Object string, Lisp_Object start, Lisp_Object end)
1994 {
1995 Lisp_Object ret;
1996 CHECK_STRING (string);
1997 /* `read_internal_start' sets `read_from_string_index'. */
1998 ret = read_internal_start (string, start, end);
1999 return Fcons (ret, make_number (read_from_string_index));
2000 }
2001
2002 /* Function to set up the global context we need in toplevel read
2003 calls. */
2004 static Lisp_Object
2005 read_internal_start (Lisp_Object stream, Lisp_Object start, Lisp_Object end)
2006 /* `start', `end' only used when stream is a string. */
2007 {
2008 Lisp_Object retval;
2009
2010 readchar_count = 0;
2011 new_backquote_flag = 0;
2012 read_objects = Qnil;
2013 if (EQ (Vread_with_symbol_positions, Qt)
2014 || EQ (Vread_with_symbol_positions, stream))
2015 Vread_symbol_positions_list = Qnil;
2016
2017 if (STRINGP (stream)
2018 || ((CONSP (stream) && STRINGP (XCAR (stream)))))
2019 {
2020 ptrdiff_t startval, endval;
2021 Lisp_Object string;
2022
2023 if (STRINGP (stream))
2024 string = stream;
2025 else
2026 string = XCAR (stream);
2027
2028 if (NILP (end))
2029 endval = SCHARS (string);
2030 else
2031 {
2032 CHECK_NUMBER (end);
2033 if (! (0 <= XINT (end) && XINT (end) <= SCHARS (string)))
2034 args_out_of_range (string, end);
2035 endval = XINT (end);
2036 }
2037
2038 if (NILP (start))
2039 startval = 0;
2040 else
2041 {
2042 CHECK_NUMBER (start);
2043 if (! (0 <= XINT (start) && XINT (start) <= endval))
2044 args_out_of_range (string, start);
2045 startval = XINT (start);
2046 }
2047 read_from_string_index = startval;
2048 read_from_string_index_byte = string_char_to_byte (string, startval);
2049 read_from_string_limit = endval;
2050 }
2051
2052 retval = read0 (stream);
2053 if (EQ (Vread_with_symbol_positions, Qt)
2054 || EQ (Vread_with_symbol_positions, stream))
2055 Vread_symbol_positions_list = Fnreverse (Vread_symbol_positions_list);
2056 return retval;
2057 }
2058 \f
2059
2060 /* Signal Qinvalid_read_syntax error.
2061 S is error string of length N (if > 0) */
2062
2063 static _Noreturn void
2064 invalid_syntax (const char *s)
2065 {
2066 xsignal1 (Qinvalid_read_syntax, build_string (s));
2067 }
2068
2069
2070 /* Use this for recursive reads, in contexts where internal tokens
2071 are not allowed. */
2072
2073 static Lisp_Object
2074 read0 (Lisp_Object readcharfun)
2075 {
2076 register Lisp_Object val;
2077 int c;
2078
2079 val = read1 (readcharfun, &c, 0);
2080 if (!c)
2081 return val;
2082
2083 xsignal1 (Qinvalid_read_syntax,
2084 Fmake_string (make_number (1), make_number (c)));
2085 }
2086 \f
2087 static ptrdiff_t read_buffer_size;
2088 static char *read_buffer;
2089
2090 /* Read a \-escape sequence, assuming we already read the `\'.
2091 If the escape sequence forces unibyte, return eight-bit char. */
2092
2093 static int
2094 read_escape (Lisp_Object readcharfun, bool stringp)
2095 {
2096 int c = READCHAR;
2097 /* \u allows up to four hex digits, \U up to eight. Default to the
2098 behavior for \u, and change this value in the case that \U is seen. */
2099 int unicode_hex_count = 4;
2100
2101 switch (c)
2102 {
2103 case -1:
2104 end_of_file_error ();
2105
2106 case 'a':
2107 return '\007';
2108 case 'b':
2109 return '\b';
2110 case 'd':
2111 return 0177;
2112 case 'e':
2113 return 033;
2114 case 'f':
2115 return '\f';
2116 case 'n':
2117 return '\n';
2118 case 'r':
2119 return '\r';
2120 case 't':
2121 return '\t';
2122 case 'v':
2123 return '\v';
2124 case '\n':
2125 return -1;
2126 case ' ':
2127 if (stringp)
2128 return -1;
2129 return ' ';
2130
2131 case 'M':
2132 c = READCHAR;
2133 if (c != '-')
2134 error ("Invalid escape character syntax");
2135 c = READCHAR;
2136 if (c == '\\')
2137 c = read_escape (readcharfun, 0);
2138 return c | meta_modifier;
2139
2140 case 'S':
2141 c = READCHAR;
2142 if (c != '-')
2143 error ("Invalid escape character syntax");
2144 c = READCHAR;
2145 if (c == '\\')
2146 c = read_escape (readcharfun, 0);
2147 return c | shift_modifier;
2148
2149 case 'H':
2150 c = READCHAR;
2151 if (c != '-')
2152 error ("Invalid escape character syntax");
2153 c = READCHAR;
2154 if (c == '\\')
2155 c = read_escape (readcharfun, 0);
2156 return c | hyper_modifier;
2157
2158 case 'A':
2159 c = READCHAR;
2160 if (c != '-')
2161 error ("Invalid escape character syntax");
2162 c = READCHAR;
2163 if (c == '\\')
2164 c = read_escape (readcharfun, 0);
2165 return c | alt_modifier;
2166
2167 case 's':
2168 c = READCHAR;
2169 if (stringp || c != '-')
2170 {
2171 UNREAD (c);
2172 return ' ';
2173 }
2174 c = READCHAR;
2175 if (c == '\\')
2176 c = read_escape (readcharfun, 0);
2177 return c | super_modifier;
2178
2179 case 'C':
2180 c = READCHAR;
2181 if (c != '-')
2182 error ("Invalid escape character syntax");
2183 case '^':
2184 c = READCHAR;
2185 if (c == '\\')
2186 c = read_escape (readcharfun, 0);
2187 if ((c & ~CHAR_MODIFIER_MASK) == '?')
2188 return 0177 | (c & CHAR_MODIFIER_MASK);
2189 else if (! SINGLE_BYTE_CHAR_P ((c & ~CHAR_MODIFIER_MASK)))
2190 return c | ctrl_modifier;
2191 /* ASCII control chars are made from letters (both cases),
2192 as well as the non-letters within 0100...0137. */
2193 else if ((c & 0137) >= 0101 && (c & 0137) <= 0132)
2194 return (c & (037 | ~0177));
2195 else if ((c & 0177) >= 0100 && (c & 0177) <= 0137)
2196 return (c & (037 | ~0177));
2197 else
2198 return c | ctrl_modifier;
2199
2200 case '0':
2201 case '1':
2202 case '2':
2203 case '3':
2204 case '4':
2205 case '5':
2206 case '6':
2207 case '7':
2208 /* An octal escape, as in ANSI C. */
2209 {
2210 register int i = c - '0';
2211 register int count = 0;
2212 while (++count < 3)
2213 {
2214 if ((c = READCHAR) >= '0' && c <= '7')
2215 {
2216 i *= 8;
2217 i += c - '0';
2218 }
2219 else
2220 {
2221 UNREAD (c);
2222 break;
2223 }
2224 }
2225
2226 if (i >= 0x80 && i < 0x100)
2227 i = BYTE8_TO_CHAR (i);
2228 return i;
2229 }
2230
2231 case 'x':
2232 /* A hex escape, as in ANSI C. */
2233 {
2234 unsigned int i = 0;
2235 int count = 0;
2236 while (1)
2237 {
2238 c = READCHAR;
2239 if (c >= '0' && c <= '9')
2240 {
2241 i *= 16;
2242 i += c - '0';
2243 }
2244 else if ((c >= 'a' && c <= 'f')
2245 || (c >= 'A' && c <= 'F'))
2246 {
2247 i *= 16;
2248 if (c >= 'a' && c <= 'f')
2249 i += c - 'a' + 10;
2250 else
2251 i += c - 'A' + 10;
2252 }
2253 else
2254 {
2255 UNREAD (c);
2256 break;
2257 }
2258 /* Allow hex escapes as large as ?\xfffffff, because some
2259 packages use them to denote characters with modifiers. */
2260 if ((CHAR_META | (CHAR_META - 1)) < i)
2261 error ("Hex character out of range: \\x%x...", i);
2262 count += count < 3;
2263 }
2264
2265 if (count < 3 && i >= 0x80)
2266 return BYTE8_TO_CHAR (i);
2267 return i;
2268 }
2269
2270 case 'U':
2271 /* Post-Unicode-2.0: Up to eight hex chars. */
2272 unicode_hex_count = 8;
2273 case 'u':
2274
2275 /* A Unicode escape. We only permit them in strings and characters,
2276 not arbitrarily in the source code, as in some other languages. */
2277 {
2278 unsigned int i = 0;
2279 int count = 0;
2280
2281 while (++count <= unicode_hex_count)
2282 {
2283 c = READCHAR;
2284 /* `isdigit' and `isalpha' may be locale-specific, which we don't
2285 want. */
2286 if (c >= '0' && c <= '9') i = (i << 4) + (c - '0');
2287 else if (c >= 'a' && c <= 'f') i = (i << 4) + (c - 'a') + 10;
2288 else if (c >= 'A' && c <= 'F') i = (i << 4) + (c - 'A') + 10;
2289 else
2290 error ("Non-hex digit used for Unicode escape");
2291 }
2292 if (i > 0x10FFFF)
2293 error ("Non-Unicode character: 0x%x", i);
2294 return i;
2295 }
2296
2297 default:
2298 return c;
2299 }
2300 }
2301
2302 /* Return the digit that CHARACTER stands for in the given BASE.
2303 Return -1 if CHARACTER is out of range for BASE,
2304 and -2 if CHARACTER is not valid for any supported BASE. */
2305 static int
2306 digit_to_number (int character, int base)
2307 {
2308 int digit;
2309
2310 if ('0' <= character && character <= '9')
2311 digit = character - '0';
2312 else if ('a' <= character && character <= 'z')
2313 digit = character - 'a' + 10;
2314 else if ('A' <= character && character <= 'Z')
2315 digit = character - 'A' + 10;
2316 else
2317 return -2;
2318
2319 return digit < base ? digit : -1;
2320 }
2321
2322 /* Read an integer in radix RADIX using READCHARFUN to read
2323 characters. RADIX must be in the interval [2..36]; if it isn't, a
2324 read error is signaled . Value is the integer read. Signals an
2325 error if encountering invalid read syntax or if RADIX is out of
2326 range. */
2327
2328 static Lisp_Object
2329 read_integer (Lisp_Object readcharfun, EMACS_INT radix)
2330 {
2331 /* Room for sign, leading 0, other digits, trailing null byte.
2332 Also, room for invalid syntax diagnostic. */
2333 char buf[max (1 + 1 + sizeof (uintmax_t) * CHAR_BIT + 1,
2334 sizeof "integer, radix " + INT_STRLEN_BOUND (EMACS_INT))];
2335
2336 int valid = -1; /* 1 if valid, 0 if not, -1 if incomplete. */
2337
2338 if (radix < 2 || radix > 36)
2339 valid = 0;
2340 else
2341 {
2342 char *p = buf;
2343 int c, digit;
2344
2345 c = READCHAR;
2346 if (c == '-' || c == '+')
2347 {
2348 *p++ = c;
2349 c = READCHAR;
2350 }
2351
2352 if (c == '0')
2353 {
2354 *p++ = c;
2355 valid = 1;
2356
2357 /* Ignore redundant leading zeros, so the buffer doesn't
2358 fill up with them. */
2359 do
2360 c = READCHAR;
2361 while (c == '0');
2362 }
2363
2364 while ((digit = digit_to_number (c, radix)) >= -1)
2365 {
2366 if (digit == -1)
2367 valid = 0;
2368 if (valid < 0)
2369 valid = 1;
2370
2371 if (p < buf + sizeof buf - 1)
2372 *p++ = c;
2373 else
2374 valid = 0;
2375
2376 c = READCHAR;
2377 }
2378
2379 UNREAD (c);
2380 *p = '\0';
2381 }
2382
2383 if (! valid)
2384 {
2385 sprintf (buf, "integer, radix %"pI"d", radix);
2386 invalid_syntax (buf);
2387 }
2388
2389 return string_to_number (buf, radix, 0);
2390 }
2391
2392
2393 /* If the next token is ')' or ']' or '.', we store that character
2394 in *PCH and the return value is not interesting. Else, we store
2395 zero in *PCH and we read and return one lisp object.
2396
2397 FIRST_IN_LIST is true if this is the first element of a list. */
2398
2399 static Lisp_Object
2400 read1 (Lisp_Object readcharfun, int *pch, bool first_in_list)
2401 {
2402 int c;
2403 bool uninterned_symbol = 0;
2404 bool multibyte;
2405
2406 *pch = 0;
2407
2408 retry:
2409
2410 c = READCHAR_REPORT_MULTIBYTE (&multibyte);
2411 if (c < 0)
2412 end_of_file_error ();
2413
2414 switch (c)
2415 {
2416 case '(':
2417 return read_list (0, readcharfun);
2418
2419 case '[':
2420 return read_vector (readcharfun, 0);
2421
2422 case ')':
2423 case ']':
2424 {
2425 *pch = c;
2426 return Qnil;
2427 }
2428
2429 case '#':
2430 c = READCHAR;
2431 if (c == 's')
2432 {
2433 c = READCHAR;
2434 if (c == '(')
2435 {
2436 /* Accept extended format for hashtables (extensible to
2437 other types), e.g.
2438 #s(hash-table size 2 test equal data (k1 v1 k2 v2)) */
2439 Lisp_Object tmp = read_list (0, readcharfun);
2440 Lisp_Object head = CAR_SAFE (tmp);
2441 Lisp_Object data = Qnil;
2442 Lisp_Object val = Qnil;
2443 /* The size is 2 * number of allowed keywords to
2444 make-hash-table. */
2445 Lisp_Object params[10];
2446 Lisp_Object ht;
2447 Lisp_Object key = Qnil;
2448 int param_count = 0;
2449
2450 if (!EQ (head, Qhash_table))
2451 error ("Invalid extended read marker at head of #s list "
2452 "(only hash-table allowed)");
2453
2454 tmp = CDR_SAFE (tmp);
2455
2456 /* This is repetitive but fast and simple. */
2457 params[param_count] = QCsize;
2458 params[param_count + 1] = Fplist_get (tmp, Qsize);
2459 if (!NILP (params[param_count + 1]))
2460 param_count += 2;
2461
2462 params[param_count] = QCtest;
2463 params[param_count + 1] = Fplist_get (tmp, Qtest);
2464 if (!NILP (params[param_count + 1]))
2465 param_count += 2;
2466
2467 params[param_count] = QCweakness;
2468 params[param_count + 1] = Fplist_get (tmp, Qweakness);
2469 if (!NILP (params[param_count + 1]))
2470 param_count += 2;
2471
2472 params[param_count] = QCrehash_size;
2473 params[param_count + 1] = Fplist_get (tmp, Qrehash_size);
2474 if (!NILP (params[param_count + 1]))
2475 param_count += 2;
2476
2477 params[param_count] = QCrehash_threshold;
2478 params[param_count + 1] = Fplist_get (tmp, Qrehash_threshold);
2479 if (!NILP (params[param_count + 1]))
2480 param_count += 2;
2481
2482 /* This is the hashtable data. */
2483 data = Fplist_get (tmp, Qdata);
2484
2485 /* Now use params to make a new hashtable and fill it. */
2486 ht = Fmake_hash_table (param_count, params);
2487
2488 while (CONSP (data))
2489 {
2490 key = XCAR (data);
2491 data = XCDR (data);
2492 if (!CONSP (data))
2493 error ("Odd number of elements in hashtable data");
2494 val = XCAR (data);
2495 data = XCDR (data);
2496 Fputhash (key, val, ht);
2497 }
2498
2499 return ht;
2500 }
2501 UNREAD (c);
2502 invalid_syntax ("#");
2503 }
2504 if (c == '^')
2505 {
2506 c = READCHAR;
2507 if (c == '[')
2508 {
2509 Lisp_Object tmp;
2510 tmp = read_vector (readcharfun, 0);
2511 if (ASIZE (tmp) < CHAR_TABLE_STANDARD_SLOTS)
2512 error ("Invalid size char-table");
2513 XSETPVECTYPE (XVECTOR (tmp), PVEC_CHAR_TABLE);
2514 return tmp;
2515 }
2516 else if (c == '^')
2517 {
2518 c = READCHAR;
2519 if (c == '[')
2520 {
2521 Lisp_Object tmp;
2522 int depth;
2523 ptrdiff_t size;
2524
2525 tmp = read_vector (readcharfun, 0);
2526 size = ASIZE (tmp);
2527 if (size == 0)
2528 error ("Invalid size char-table");
2529 if (! RANGED_INTEGERP (1, AREF (tmp, 0), 3))
2530 error ("Invalid depth in char-table");
2531 depth = XINT (AREF (tmp, 0));
2532 if (chartab_size[depth] != size - 2)
2533 error ("Invalid size char-table");
2534 XSETPVECTYPE (XVECTOR (tmp), PVEC_SUB_CHAR_TABLE);
2535 return tmp;
2536 }
2537 invalid_syntax ("#^^");
2538 }
2539 invalid_syntax ("#^");
2540 }
2541 if (c == '&')
2542 {
2543 Lisp_Object length;
2544 length = read1 (readcharfun, pch, first_in_list);
2545 c = READCHAR;
2546 if (c == '"')
2547 {
2548 Lisp_Object tmp, val;
2549 EMACS_INT size_in_chars
2550 = ((XFASTINT (length) + BOOL_VECTOR_BITS_PER_CHAR - 1)
2551 / BOOL_VECTOR_BITS_PER_CHAR);
2552
2553 UNREAD (c);
2554 tmp = read1 (readcharfun, pch, first_in_list);
2555 if (STRING_MULTIBYTE (tmp)
2556 || (size_in_chars != SCHARS (tmp)
2557 /* We used to print 1 char too many
2558 when the number of bits was a multiple of 8.
2559 Accept such input in case it came from an old
2560 version. */
2561 && ! (XFASTINT (length)
2562 == (SCHARS (tmp) - 1) * BOOL_VECTOR_BITS_PER_CHAR)))
2563 invalid_syntax ("#&...");
2564
2565 val = Fmake_bool_vector (length, Qnil);
2566 memcpy (XBOOL_VECTOR (val)->data, SDATA (tmp), size_in_chars);
2567 /* Clear the extraneous bits in the last byte. */
2568 if (XINT (length) != size_in_chars * BOOL_VECTOR_BITS_PER_CHAR)
2569 XBOOL_VECTOR (val)->data[size_in_chars - 1]
2570 &= (1 << (XINT (length) % BOOL_VECTOR_BITS_PER_CHAR)) - 1;
2571 return val;
2572 }
2573 invalid_syntax ("#&...");
2574 }
2575 if (c == '[')
2576 {
2577 /* Accept compiled functions at read-time so that we don't have to
2578 build them using function calls. */
2579 Lisp_Object tmp;
2580 tmp = read_vector (readcharfun, 1);
2581 make_byte_code (XVECTOR (tmp));
2582 return tmp;
2583 }
2584 if (c == '(')
2585 {
2586 Lisp_Object tmp;
2587 struct gcpro gcpro1;
2588 int ch;
2589
2590 /* Read the string itself. */
2591 tmp = read1 (readcharfun, &ch, 0);
2592 if (ch != 0 || !STRINGP (tmp))
2593 invalid_syntax ("#");
2594 GCPRO1 (tmp);
2595 /* Read the intervals and their properties. */
2596 while (1)
2597 {
2598 Lisp_Object beg, end, plist;
2599
2600 beg = read1 (readcharfun, &ch, 0);
2601 end = plist = Qnil;
2602 if (ch == ')')
2603 break;
2604 if (ch == 0)
2605 end = read1 (readcharfun, &ch, 0);
2606 if (ch == 0)
2607 plist = read1 (readcharfun, &ch, 0);
2608 if (ch)
2609 invalid_syntax ("Invalid string property list");
2610 Fset_text_properties (beg, end, plist, tmp);
2611 }
2612 UNGCPRO;
2613 return tmp;
2614 }
2615
2616 /* #@NUMBER is used to skip NUMBER following bytes.
2617 That's used in .elc files to skip over doc strings
2618 and function definitions. */
2619 if (c == '@')
2620 {
2621 enum { extra = 100 };
2622 ptrdiff_t i, nskip = 0;
2623
2624 /* Read a decimal integer. */
2625 while ((c = READCHAR) >= 0
2626 && c >= '0' && c <= '9')
2627 {
2628 if ((STRING_BYTES_BOUND - extra) / 10 <= nskip)
2629 string_overflow ();
2630 nskip *= 10;
2631 nskip += c - '0';
2632 }
2633 if (nskip > 0)
2634 /* We can't use UNREAD here, because in the code below we side-step
2635 READCHAR. Instead, assume the first char after #@NNN occupies
2636 a single byte, which is the case normally since it's just
2637 a space. */
2638 nskip--;
2639 else
2640 UNREAD (c);
2641
2642 if (load_force_doc_strings
2643 && (FROM_FILE_P (readcharfun)))
2644 {
2645 /* If we are supposed to force doc strings into core right now,
2646 record the last string that we skipped,
2647 and record where in the file it comes from. */
2648
2649 /* But first exchange saved_doc_string
2650 with prev_saved_doc_string, so we save two strings. */
2651 {
2652 char *temp = saved_doc_string;
2653 ptrdiff_t temp_size = saved_doc_string_size;
2654 file_offset temp_pos = saved_doc_string_position;
2655 ptrdiff_t temp_len = saved_doc_string_length;
2656
2657 saved_doc_string = prev_saved_doc_string;
2658 saved_doc_string_size = prev_saved_doc_string_size;
2659 saved_doc_string_position = prev_saved_doc_string_position;
2660 saved_doc_string_length = prev_saved_doc_string_length;
2661
2662 prev_saved_doc_string = temp;
2663 prev_saved_doc_string_size = temp_size;
2664 prev_saved_doc_string_position = temp_pos;
2665 prev_saved_doc_string_length = temp_len;
2666 }
2667
2668 if (saved_doc_string_size == 0)
2669 {
2670 saved_doc_string = xmalloc (nskip + extra);
2671 saved_doc_string_size = nskip + extra;
2672 }
2673 if (nskip > saved_doc_string_size)
2674 {
2675 saved_doc_string = xrealloc (saved_doc_string, nskip + extra);
2676 saved_doc_string_size = nskip + extra;
2677 }
2678
2679 saved_doc_string_position = file_tell (instream);
2680
2681 /* Copy that many characters into saved_doc_string. */
2682 block_input ();
2683 for (i = 0; i < nskip && c >= 0; i++)
2684 saved_doc_string[i] = c = getc (instream);
2685 unblock_input ();
2686
2687 saved_doc_string_length = i;
2688 }
2689 else
2690 /* Skip that many bytes. */
2691 skip_dyn_bytes (readcharfun, nskip);
2692
2693 goto retry;
2694 }
2695 if (c == '!')
2696 {
2697 /* #! appears at the beginning of an executable file.
2698 Skip the first line. */
2699 while (c != '\n' && c >= 0)
2700 c = READCHAR;
2701 goto retry;
2702 }
2703 if (c == '$')
2704 return Vload_file_name;
2705 if (c == '\'')
2706 return Fcons (Qfunction, Fcons (read0 (readcharfun), Qnil));
2707 /* #:foo is the uninterned symbol named foo. */
2708 if (c == ':')
2709 {
2710 uninterned_symbol = 1;
2711 c = READCHAR;
2712 if (!(c > 040
2713 && c != 0xa0 /* NBSP */
2714 && (c >= 0200
2715 || strchr ("\"';()[]#`,", c) == NULL)))
2716 {
2717 /* No symbol character follows, this is the empty
2718 symbol. */
2719 UNREAD (c);
2720 return Fmake_symbol (empty_unibyte_string);
2721 }
2722 goto read_symbol;
2723 }
2724 /* ## is the empty symbol. */
2725 if (c == '#')
2726 return Fintern (empty_unibyte_string, Qnil);
2727 /* Reader forms that can reuse previously read objects. */
2728 if (c >= '0' && c <= '9')
2729 {
2730 EMACS_INT n = 0;
2731 Lisp_Object tem;
2732
2733 /* Read a non-negative integer. */
2734 while (c >= '0' && c <= '9')
2735 {
2736 if (MOST_POSITIVE_FIXNUM / 10 < n
2737 || MOST_POSITIVE_FIXNUM < n * 10 + c - '0')
2738 n = MOST_POSITIVE_FIXNUM + 1;
2739 else
2740 n = n * 10 + c - '0';
2741 c = READCHAR;
2742 }
2743
2744 if (n <= MOST_POSITIVE_FIXNUM)
2745 {
2746 if (c == 'r' || c == 'R')
2747 return read_integer (readcharfun, n);
2748
2749 if (! NILP (Vread_circle))
2750 {
2751 /* #n=object returns object, but associates it with
2752 n for #n#. */
2753 if (c == '=')
2754 {
2755 /* Make a placeholder for #n# to use temporarily. */
2756 Lisp_Object placeholder;
2757 Lisp_Object cell;
2758
2759 placeholder = Fcons (Qnil, Qnil);
2760 cell = Fcons (make_number (n), placeholder);
2761 read_objects = Fcons (cell, read_objects);
2762
2763 /* Read the object itself. */
2764 tem = read0 (readcharfun);
2765
2766 /* Now put it everywhere the placeholder was... */
2767 substitute_object_in_subtree (tem, placeholder);
2768
2769 /* ...and #n# will use the real value from now on. */
2770 Fsetcdr (cell, tem);
2771
2772 return tem;
2773 }
2774
2775 /* #n# returns a previously read object. */
2776 if (c == '#')
2777 {
2778 tem = Fassq (make_number (n), read_objects);
2779 if (CONSP (tem))
2780 return XCDR (tem);
2781 }
2782 }
2783 }
2784 /* Fall through to error message. */
2785 }
2786 else if (c == 'x' || c == 'X')
2787 return read_integer (readcharfun, 16);
2788 else if (c == 'o' || c == 'O')
2789 return read_integer (readcharfun, 8);
2790 else if (c == 'b' || c == 'B')
2791 return read_integer (readcharfun, 2);
2792
2793 UNREAD (c);
2794 invalid_syntax ("#");
2795
2796 case ';':
2797 while ((c = READCHAR) >= 0 && c != '\n');
2798 goto retry;
2799
2800 case '\'':
2801 {
2802 return Fcons (Qquote, Fcons (read0 (readcharfun), Qnil));
2803 }
2804
2805 case '`':
2806 {
2807 int next_char = READCHAR;
2808 UNREAD (next_char);
2809 /* Transition from old-style to new-style:
2810 If we see "(`" it used to mean old-style, which usually works
2811 fine because ` should almost never appear in such a position
2812 for new-style. But occasionally we need "(`" to mean new
2813 style, so we try to distinguish the two by the fact that we
2814 can either write "( `foo" or "(` foo", where the first
2815 intends to use new-style whereas the second intends to use
2816 old-style. For Emacs-25, we should completely remove this
2817 first_in_list exception (old-style can still be obtained via
2818 "(\`" anyway). */
2819 if (!new_backquote_flag && first_in_list && next_char == ' ')
2820 {
2821 Vold_style_backquotes = Qt;
2822 goto default_label;
2823 }
2824 else
2825 {
2826 Lisp_Object value;
2827 bool saved_new_backquote_flag = new_backquote_flag;
2828
2829 new_backquote_flag = 1;
2830 value = read0 (readcharfun);
2831 new_backquote_flag = saved_new_backquote_flag;
2832
2833 return Fcons (Qbackquote, Fcons (value, Qnil));
2834 }
2835 }
2836 case ',':
2837 {
2838 int next_char = READCHAR;
2839 UNREAD (next_char);
2840 /* Transition from old-style to new-style:
2841 It used to be impossible to have a new-style , other than within
2842 a new-style `. This is sufficient when ` and , are used in the
2843 normal way, but ` and , can also appear in args to macros that
2844 will not interpret them in the usual way, in which case , may be
2845 used without any ` anywhere near.
2846 So we now use the same heuristic as for backquote: old-style
2847 unquotes are only recognized when first on a list, and when
2848 followed by a space.
2849 Because it's more difficult to peek 2 chars ahead, a new-style
2850 ,@ can still not be used outside of a `, unless it's in the middle
2851 of a list. */
2852 if (new_backquote_flag
2853 || !first_in_list
2854 || (next_char != ' ' && next_char != '@'))
2855 {
2856 Lisp_Object comma_type = Qnil;
2857 Lisp_Object value;
2858 int ch = READCHAR;
2859
2860 if (ch == '@')
2861 comma_type = Qcomma_at;
2862 else if (ch == '.')
2863 comma_type = Qcomma_dot;
2864 else
2865 {
2866 if (ch >= 0) UNREAD (ch);
2867 comma_type = Qcomma;
2868 }
2869
2870 value = read0 (readcharfun);
2871 return Fcons (comma_type, Fcons (value, Qnil));
2872 }
2873 else
2874 {
2875 Vold_style_backquotes = Qt;
2876 goto default_label;
2877 }
2878 }
2879 case '?':
2880 {
2881 int modifiers;
2882 int next_char;
2883 bool ok;
2884
2885 c = READCHAR;
2886 if (c < 0)
2887 end_of_file_error ();
2888
2889 /* Accept `single space' syntax like (list ? x) where the
2890 whitespace character is SPC or TAB.
2891 Other literal whitespace like NL, CR, and FF are not accepted,
2892 as there are well-established escape sequences for these. */
2893 if (c == ' ' || c == '\t')
2894 return make_number (c);
2895
2896 if (c == '\\')
2897 c = read_escape (readcharfun, 0);
2898 modifiers = c & CHAR_MODIFIER_MASK;
2899 c &= ~CHAR_MODIFIER_MASK;
2900 if (CHAR_BYTE8_P (c))
2901 c = CHAR_TO_BYTE8 (c);
2902 c |= modifiers;
2903
2904 next_char = READCHAR;
2905 ok = (next_char <= 040
2906 || (next_char < 0200
2907 && strchr ("\"';()[]#?`,.", next_char) != NULL));
2908 UNREAD (next_char);
2909 if (ok)
2910 return make_number (c);
2911
2912 invalid_syntax ("?");
2913 }
2914
2915 case '"':
2916 {
2917 char *p = read_buffer;
2918 char *end = read_buffer + read_buffer_size;
2919 int ch;
2920 /* True if we saw an escape sequence specifying
2921 a multibyte character. */
2922 bool force_multibyte = 0;
2923 /* True if we saw an escape sequence specifying
2924 a single-byte character. */
2925 bool force_singlebyte = 0;
2926 bool cancel = 0;
2927 ptrdiff_t nchars = 0;
2928
2929 while ((ch = READCHAR) >= 0
2930 && ch != '\"')
2931 {
2932 if (end - p < MAX_MULTIBYTE_LENGTH)
2933 {
2934 ptrdiff_t offset = p - read_buffer;
2935 if (min (PTRDIFF_MAX, SIZE_MAX) / 2 < read_buffer_size)
2936 memory_full (SIZE_MAX);
2937 read_buffer = xrealloc (read_buffer, read_buffer_size * 2);
2938 read_buffer_size *= 2;
2939 p = read_buffer + offset;
2940 end = read_buffer + read_buffer_size;
2941 }
2942
2943 if (ch == '\\')
2944 {
2945 int modifiers;
2946
2947 ch = read_escape (readcharfun, 1);
2948
2949 /* CH is -1 if \ newline has just been seen. */
2950 if (ch == -1)
2951 {
2952 if (p == read_buffer)
2953 cancel = 1;
2954 continue;
2955 }
2956
2957 modifiers = ch & CHAR_MODIFIER_MASK;
2958 ch = ch & ~CHAR_MODIFIER_MASK;
2959
2960 if (CHAR_BYTE8_P (ch))
2961 force_singlebyte = 1;
2962 else if (! ASCII_CHAR_P (ch))
2963 force_multibyte = 1;
2964 else /* I.e. ASCII_CHAR_P (ch). */
2965 {
2966 /* Allow `\C- ' and `\C-?'. */
2967 if (modifiers == CHAR_CTL)
2968 {
2969 if (ch == ' ')
2970 ch = 0, modifiers = 0;
2971 else if (ch == '?')
2972 ch = 127, modifiers = 0;
2973 }
2974 if (modifiers & CHAR_SHIFT)
2975 {
2976 /* Shift modifier is valid only with [A-Za-z]. */
2977 if (ch >= 'A' && ch <= 'Z')
2978 modifiers &= ~CHAR_SHIFT;
2979 else if (ch >= 'a' && ch <= 'z')
2980 ch -= ('a' - 'A'), modifiers &= ~CHAR_SHIFT;
2981 }
2982
2983 if (modifiers & CHAR_META)
2984 {
2985 /* Move the meta bit to the right place for a
2986 string. */
2987 modifiers &= ~CHAR_META;
2988 ch = BYTE8_TO_CHAR (ch | 0x80);
2989 force_singlebyte = 1;
2990 }
2991 }
2992
2993 /* Any modifiers remaining are invalid. */
2994 if (modifiers)
2995 error ("Invalid modifier in string");
2996 p += CHAR_STRING (ch, (unsigned char *) p);
2997 }
2998 else
2999 {
3000 p += CHAR_STRING (ch, (unsigned char *) p);
3001 if (CHAR_BYTE8_P (ch))
3002 force_singlebyte = 1;
3003 else if (! ASCII_CHAR_P (ch))
3004 force_multibyte = 1;
3005 }
3006 nchars++;
3007 }
3008
3009 if (ch < 0)
3010 end_of_file_error ();
3011
3012 /* If purifying, and string starts with \ newline,
3013 return zero instead. This is for doc strings
3014 that we are really going to find in etc/DOC.nn.nn. */
3015 if (!NILP (Vpurify_flag) && NILP (Vdoc_file_name) && cancel)
3016 return make_number (0);
3017
3018 if (! force_multibyte && force_singlebyte)
3019 {
3020 /* READ_BUFFER contains raw 8-bit bytes and no multibyte
3021 forms. Convert it to unibyte. */
3022 nchars = str_as_unibyte ((unsigned char *) read_buffer,
3023 p - read_buffer);
3024 p = read_buffer + nchars;
3025 }
3026
3027 return make_specified_string (read_buffer, nchars, p - read_buffer,
3028 (force_multibyte
3029 || (p - read_buffer != nchars)));
3030 }
3031
3032 case '.':
3033 {
3034 int next_char = READCHAR;
3035 UNREAD (next_char);
3036
3037 if (next_char <= 040
3038 || (next_char < 0200
3039 && strchr ("\"';([#?`,", next_char) != NULL))
3040 {
3041 *pch = c;
3042 return Qnil;
3043 }
3044
3045 /* Otherwise, we fall through! Note that the atom-reading loop
3046 below will now loop at least once, assuring that we will not
3047 try to UNREAD two characters in a row. */
3048 }
3049 default:
3050 default_label:
3051 if (c <= 040) goto retry;
3052 if (c == 0xa0) /* NBSP */
3053 goto retry;
3054
3055 read_symbol:
3056 {
3057 char *p = read_buffer;
3058 bool quoted = 0;
3059 EMACS_INT start_position = readchar_count - 1;
3060
3061 {
3062 char *end = read_buffer + read_buffer_size;
3063
3064 do
3065 {
3066 if (end - p < MAX_MULTIBYTE_LENGTH)
3067 {
3068 ptrdiff_t offset = p - read_buffer;
3069 if (min (PTRDIFF_MAX, SIZE_MAX) / 2 < read_buffer_size)
3070 memory_full (SIZE_MAX);
3071 read_buffer = xrealloc (read_buffer, read_buffer_size * 2);
3072 read_buffer_size *= 2;
3073 p = read_buffer + offset;
3074 end = read_buffer + read_buffer_size;
3075 }
3076
3077 if (c == '\\')
3078 {
3079 c = READCHAR;
3080 if (c == -1)
3081 end_of_file_error ();
3082 quoted = 1;
3083 }
3084
3085 if (multibyte)
3086 p += CHAR_STRING (c, (unsigned char *) p);
3087 else
3088 *p++ = c;
3089 c = READCHAR;
3090 }
3091 while (c > 040
3092 && c != 0xa0 /* NBSP */
3093 && (c >= 0200
3094 || strchr ("\"';()[]#`,", c) == NULL));
3095
3096 if (p == end)
3097 {
3098 ptrdiff_t offset = p - read_buffer;
3099 if (min (PTRDIFF_MAX, SIZE_MAX) / 2 < read_buffer_size)
3100 memory_full (SIZE_MAX);
3101 read_buffer = xrealloc (read_buffer, read_buffer_size * 2);
3102 read_buffer_size *= 2;
3103 p = read_buffer + offset;
3104 end = read_buffer + read_buffer_size;
3105 }
3106 *p = 0;
3107 UNREAD (c);
3108 }
3109
3110 if (!quoted && !uninterned_symbol)
3111 {
3112 Lisp_Object result = string_to_number (read_buffer, 10, 0);
3113 if (! NILP (result))
3114 return result;
3115 }
3116 {
3117 Lisp_Object name, result;
3118 ptrdiff_t nbytes = p - read_buffer;
3119 ptrdiff_t nchars
3120 = (multibyte
3121 ? multibyte_chars_in_text ((unsigned char *) read_buffer,
3122 nbytes)
3123 : nbytes);
3124
3125 name = ((uninterned_symbol && ! NILP (Vpurify_flag)
3126 ? make_pure_string : make_specified_string)
3127 (read_buffer, nchars, nbytes, multibyte));
3128 result = (uninterned_symbol ? Fmake_symbol (name)
3129 : Fintern (name, Qnil));
3130
3131 if (EQ (Vread_with_symbol_positions, Qt)
3132 || EQ (Vread_with_symbol_positions, readcharfun))
3133 Vread_symbol_positions_list
3134 = Fcons (Fcons (result, make_number (start_position)),
3135 Vread_symbol_positions_list);
3136 return result;
3137 }
3138 }
3139 }
3140 }
3141 \f
3142
3143 /* List of nodes we've seen during substitute_object_in_subtree. */
3144 static Lisp_Object seen_list;
3145
3146 static void
3147 substitute_object_in_subtree (Lisp_Object object, Lisp_Object placeholder)
3148 {
3149 Lisp_Object check_object;
3150
3151 /* We haven't seen any objects when we start. */
3152 seen_list = Qnil;
3153
3154 /* Make all the substitutions. */
3155 check_object
3156 = substitute_object_recurse (object, placeholder, object);
3157
3158 /* Clear seen_list because we're done with it. */
3159 seen_list = Qnil;
3160
3161 /* The returned object here is expected to always eq the
3162 original. */
3163 if (!EQ (check_object, object))
3164 error ("Unexpected mutation error in reader");
3165 }
3166
3167 /* Feval doesn't get called from here, so no gc protection is needed. */
3168 #define SUBSTITUTE(get_val, set_val) \
3169 do { \
3170 Lisp_Object old_value = get_val; \
3171 Lisp_Object true_value \
3172 = substitute_object_recurse (object, placeholder, \
3173 old_value); \
3174 \
3175 if (!EQ (old_value, true_value)) \
3176 { \
3177 set_val; \
3178 } \
3179 } while (0)
3180
3181 static Lisp_Object
3182 substitute_object_recurse (Lisp_Object object, Lisp_Object placeholder, Lisp_Object subtree)
3183 {
3184 /* If we find the placeholder, return the target object. */
3185 if (EQ (placeholder, subtree))
3186 return object;
3187
3188 /* If we've been to this node before, don't explore it again. */
3189 if (!EQ (Qnil, Fmemq (subtree, seen_list)))
3190 return subtree;
3191
3192 /* If this node can be the entry point to a cycle, remember that
3193 we've seen it. It can only be such an entry point if it was made
3194 by #n=, which means that we can find it as a value in
3195 read_objects. */
3196 if (!EQ (Qnil, Frassq (subtree, read_objects)))
3197 seen_list = Fcons (subtree, seen_list);
3198
3199 /* Recurse according to subtree's type.
3200 Every branch must return a Lisp_Object. */
3201 switch (XTYPE (subtree))
3202 {
3203 case Lisp_Vectorlike:
3204 {
3205 ptrdiff_t i, length = 0;
3206 if (BOOL_VECTOR_P (subtree))
3207 return subtree; /* No sub-objects anyway. */
3208 else if (CHAR_TABLE_P (subtree) || SUB_CHAR_TABLE_P (subtree)
3209 || COMPILEDP (subtree))
3210 length = ASIZE (subtree) & PSEUDOVECTOR_SIZE_MASK;
3211 else if (VECTORP (subtree))
3212 length = ASIZE (subtree);
3213 else
3214 /* An unknown pseudovector may contain non-Lisp fields, so we
3215 can't just blindly traverse all its fields. We used to call
3216 `Flength' which signaled `sequencep', so I just preserved this
3217 behavior. */
3218 wrong_type_argument (Qsequencep, subtree);
3219
3220 for (i = 0; i < length; i++)
3221 SUBSTITUTE (AREF (subtree, i),
3222 ASET (subtree, i, true_value));
3223 return subtree;
3224 }
3225
3226 case Lisp_Cons:
3227 {
3228 SUBSTITUTE (XCAR (subtree),
3229 XSETCAR (subtree, true_value));
3230 SUBSTITUTE (XCDR (subtree),
3231 XSETCDR (subtree, true_value));
3232 return subtree;
3233 }
3234
3235 case Lisp_String:
3236 {
3237 /* Check for text properties in each interval.
3238 substitute_in_interval contains part of the logic. */
3239
3240 INTERVAL root_interval = string_intervals (subtree);
3241 Lisp_Object arg = Fcons (object, placeholder);
3242
3243 traverse_intervals_noorder (root_interval,
3244 &substitute_in_interval, arg);
3245
3246 return subtree;
3247 }
3248
3249 /* Other types don't recurse any further. */
3250 default:
3251 return subtree;
3252 }
3253 }
3254
3255 /* Helper function for substitute_object_recurse. */
3256 static void
3257 substitute_in_interval (INTERVAL interval, Lisp_Object arg)
3258 {
3259 Lisp_Object object = Fcar (arg);
3260 Lisp_Object placeholder = Fcdr (arg);
3261
3262 SUBSTITUTE (interval->plist, set_interval_plist (interval, true_value));
3263 }
3264
3265 \f
3266 #define LEAD_INT 1
3267 #define DOT_CHAR 2
3268 #define TRAIL_INT 4
3269 #define E_EXP 16
3270
3271
3272 /* Convert STRING to a number, assuming base BASE. Return a fixnum if CP has
3273 integer syntax and fits in a fixnum, else return the nearest float if CP has
3274 either floating point or integer syntax and BASE is 10, else return nil. If
3275 IGNORE_TRAILING, consider just the longest prefix of CP that has
3276 valid floating point syntax. Signal an overflow if BASE is not 10 and the
3277 number has integer syntax but does not fit. */
3278
3279 Lisp_Object
3280 string_to_number (char const *string, int base, bool ignore_trailing)
3281 {
3282 int state;
3283 char const *cp = string;
3284 int leading_digit;
3285 bool float_syntax = 0;
3286 double value = 0;
3287
3288 /* Compute NaN and infinities using a variable, to cope with compilers that
3289 think they are smarter than we are. */
3290 double zero = 0;
3291
3292 /* Negate the value ourselves. This treats 0, NaNs, and infinity properly on
3293 IEEE floating point hosts, and works around a formerly-common bug where
3294 atof ("-0.0") drops the sign. */
3295 bool negative = *cp == '-';
3296
3297 bool signedp = negative || *cp == '+';
3298 cp += signedp;
3299
3300 state = 0;
3301
3302 leading_digit = digit_to_number (*cp, base);
3303 if (leading_digit >= 0)
3304 {
3305 state |= LEAD_INT;
3306 do
3307 ++cp;
3308 while (digit_to_number (*cp, base) >= 0);
3309 }
3310 if (*cp == '.')
3311 {
3312 state |= DOT_CHAR;
3313 cp++;
3314 }
3315
3316 if (base == 10)
3317 {
3318 if ('0' <= *cp && *cp <= '9')
3319 {
3320 state |= TRAIL_INT;
3321 do
3322 cp++;
3323 while ('0' <= *cp && *cp <= '9');
3324 }
3325 if (*cp == 'e' || *cp == 'E')
3326 {
3327 char const *ecp = cp;
3328 cp++;
3329 if (*cp == '+' || *cp == '-')
3330 cp++;
3331 if ('0' <= *cp && *cp <= '9')
3332 {
3333 state |= E_EXP;
3334 do
3335 cp++;
3336 while ('0' <= *cp && *cp <= '9');
3337 }
3338 else if (cp[-1] == '+'
3339 && cp[0] == 'I' && cp[1] == 'N' && cp[2] == 'F')
3340 {
3341 state |= E_EXP;
3342 cp += 3;
3343 value = 1.0 / zero;
3344 }
3345 else if (cp[-1] == '+'
3346 && cp[0] == 'N' && cp[1] == 'a' && cp[2] == 'N')
3347 {
3348 state |= E_EXP;
3349 cp += 3;
3350 value = zero / zero;
3351
3352 /* If that made a "negative" NaN, negate it. */
3353 {
3354 int i;
3355 union { double d; char c[sizeof (double)]; }
3356 u_data, u_minus_zero;
3357 u_data.d = value;
3358 u_minus_zero.d = -0.0;
3359 for (i = 0; i < sizeof (double); i++)
3360 if (u_data.c[i] & u_minus_zero.c[i])
3361 {
3362 value = -value;
3363 break;
3364 }
3365 }
3366 /* Now VALUE is a positive NaN. */
3367 }
3368 else
3369 cp = ecp;
3370 }
3371
3372 float_syntax = ((state & (DOT_CHAR|TRAIL_INT)) == (DOT_CHAR|TRAIL_INT)
3373 || state == (LEAD_INT|E_EXP));
3374 }
3375
3376 /* Return nil if the number uses invalid syntax. If IGNORE_TRAILING, accept
3377 any prefix that matches. Otherwise, the entire string must match. */
3378 if (! (ignore_trailing
3379 ? ((state & LEAD_INT) != 0 || float_syntax)
3380 : (!*cp && ((state & ~DOT_CHAR) == LEAD_INT || float_syntax))))
3381 return Qnil;
3382
3383 /* If the number uses integer and not float syntax, and is in C-language
3384 range, use its value, preferably as a fixnum. */
3385 if (leading_digit >= 0 && ! float_syntax)
3386 {
3387 uintmax_t n;
3388
3389 /* Fast special case for single-digit integers. This also avoids a
3390 glitch when BASE is 16 and IGNORE_TRAILING, because in that
3391 case some versions of strtoumax accept numbers like "0x1" that Emacs
3392 does not allow. */
3393 if (digit_to_number (string[signedp + 1], base) < 0)
3394 return make_number (negative ? -leading_digit : leading_digit);
3395
3396 errno = 0;
3397 n = strtoumax (string + signedp, NULL, base);
3398 if (errno == ERANGE)
3399 {
3400 /* Unfortunately there's no simple and accurate way to convert
3401 non-base-10 numbers that are out of C-language range. */
3402 if (base != 10)
3403 xsignal1 (Qoverflow_error, build_string (string));
3404 }
3405 else if (n <= (negative ? -MOST_NEGATIVE_FIXNUM : MOST_POSITIVE_FIXNUM))
3406 {
3407 EMACS_INT signed_n = n;
3408 return make_number (negative ? -signed_n : signed_n);
3409 }
3410 else
3411 value = n;
3412 }
3413
3414 /* Either the number uses float syntax, or it does not fit into a fixnum.
3415 Convert it from string to floating point, unless the value is already
3416 known because it is an infinity, a NAN, or its absolute value fits in
3417 uintmax_t. */
3418 if (! value)
3419 value = atof (string + signedp);
3420
3421 return make_float (negative ? -value : value);
3422 }
3423
3424 \f
3425 static Lisp_Object
3426 read_vector (Lisp_Object readcharfun, bool bytecodeflag)
3427 {
3428 ptrdiff_t i, size;
3429 Lisp_Object *ptr;
3430 Lisp_Object tem, item, vector;
3431 struct Lisp_Cons *otem;
3432 Lisp_Object len;
3433
3434 tem = read_list (1, readcharfun);
3435 len = Flength (tem);
3436 vector = Fmake_vector (len, Qnil);
3437
3438 size = ASIZE (vector);
3439 ptr = XVECTOR (vector)->contents;
3440 for (i = 0; i < size; i++)
3441 {
3442 item = Fcar (tem);
3443 /* If `load-force-doc-strings' is t when reading a lazily-loaded
3444 bytecode object, the docstring containing the bytecode and
3445 constants values must be treated as unibyte and passed to
3446 Fread, to get the actual bytecode string and constants vector. */
3447 if (bytecodeflag && load_force_doc_strings)
3448 {
3449 if (i == COMPILED_BYTECODE)
3450 {
3451 if (!STRINGP (item))
3452 error ("Invalid byte code");
3453
3454 /* Delay handling the bytecode slot until we know whether
3455 it is lazily-loaded (we can tell by whether the
3456 constants slot is nil). */
3457 ASET (vector, COMPILED_CONSTANTS, item);
3458 item = Qnil;
3459 }
3460 else if (i == COMPILED_CONSTANTS)
3461 {
3462 Lisp_Object bytestr = ptr[COMPILED_CONSTANTS];
3463
3464 if (NILP (item))
3465 {
3466 /* Coerce string to unibyte (like string-as-unibyte,
3467 but without generating extra garbage and
3468 guaranteeing no change in the contents). */
3469 STRING_SET_CHARS (bytestr, SBYTES (bytestr));
3470 STRING_SET_UNIBYTE (bytestr);
3471
3472 item = Fread (Fcons (bytestr, readcharfun));
3473 if (!CONSP (item))
3474 error ("Invalid byte code");
3475
3476 otem = XCONS (item);
3477 bytestr = XCAR (item);
3478 item = XCDR (item);
3479 free_cons (otem);
3480 }
3481
3482 /* Now handle the bytecode slot. */
3483 ASET (vector, COMPILED_BYTECODE, bytestr);
3484 }
3485 else if (i == COMPILED_DOC_STRING
3486 && STRINGP (item)
3487 && ! STRING_MULTIBYTE (item))
3488 {
3489 if (EQ (readcharfun, Qget_emacs_mule_file_char))
3490 item = Fdecode_coding_string (item, Qemacs_mule, Qnil, Qnil);
3491 else
3492 item = Fstring_as_multibyte (item);
3493 }
3494 }
3495 ASET (vector, i, item);
3496 otem = XCONS (tem);
3497 tem = Fcdr (tem);
3498 free_cons (otem);
3499 }
3500 return vector;
3501 }
3502
3503 /* FLAG means check for ] to terminate rather than ) and . */
3504
3505 static Lisp_Object
3506 read_list (bool flag, Lisp_Object readcharfun)
3507 {
3508 Lisp_Object val, tail;
3509 Lisp_Object elt, tem;
3510 struct gcpro gcpro1, gcpro2;
3511 /* 0 is the normal case.
3512 1 means this list is a doc reference; replace it with the number 0.
3513 2 means this list is a doc reference; replace it with the doc string. */
3514 int doc_reference = 0;
3515
3516 /* Initialize this to 1 if we are reading a list. */
3517 bool first_in_list = flag <= 0;
3518
3519 val = Qnil;
3520 tail = Qnil;
3521
3522 while (1)
3523 {
3524 int ch;
3525 GCPRO2 (val, tail);
3526 elt = read1 (readcharfun, &ch, first_in_list);
3527 UNGCPRO;
3528
3529 first_in_list = 0;
3530
3531 /* While building, if the list starts with #$, treat it specially. */
3532 if (EQ (elt, Vload_file_name)
3533 && ! NILP (elt)
3534 && !NILP (Vpurify_flag))
3535 {
3536 if (NILP (Vdoc_file_name))
3537 /* We have not yet called Snarf-documentation, so assume
3538 this file is described in the DOC-MM.NN file
3539 and Snarf-documentation will fill in the right value later.
3540 For now, replace the whole list with 0. */
3541 doc_reference = 1;
3542 else
3543 /* We have already called Snarf-documentation, so make a relative
3544 file name for this file, so it can be found properly
3545 in the installed Lisp directory.
3546 We don't use Fexpand_file_name because that would make
3547 the directory absolute now. */
3548 elt = concat2 (build_string ("../lisp/"),
3549 Ffile_name_nondirectory (elt));
3550 }
3551 else if (EQ (elt, Vload_file_name)
3552 && ! NILP (elt)
3553 && load_force_doc_strings)
3554 doc_reference = 2;
3555
3556 if (ch)
3557 {
3558 if (flag > 0)
3559 {
3560 if (ch == ']')
3561 return val;
3562 invalid_syntax (") or . in a vector");
3563 }
3564 if (ch == ')')
3565 return val;
3566 if (ch == '.')
3567 {
3568 GCPRO2 (val, tail);
3569 if (!NILP (tail))
3570 XSETCDR (tail, read0 (readcharfun));
3571 else
3572 val = read0 (readcharfun);
3573 read1 (readcharfun, &ch, 0);
3574 UNGCPRO;
3575 if (ch == ')')
3576 {
3577 if (doc_reference == 1)
3578 return make_number (0);
3579 if (doc_reference == 2 && INTEGERP (XCDR (val)))
3580 {
3581 char *saved = NULL;
3582 file_offset saved_position;
3583 /* Get a doc string from the file we are loading.
3584 If it's in saved_doc_string, get it from there.
3585
3586 Here, we don't know if the string is a
3587 bytecode string or a doc string. As a
3588 bytecode string must be unibyte, we always
3589 return a unibyte string. If it is actually a
3590 doc string, caller must make it
3591 multibyte. */
3592
3593 /* Position is negative for user variables. */
3594 EMACS_INT pos = eabs (XINT (XCDR (val)));
3595 if (pos >= saved_doc_string_position
3596 && pos < (saved_doc_string_position
3597 + saved_doc_string_length))
3598 {
3599 saved = saved_doc_string;
3600 saved_position = saved_doc_string_position;
3601 }
3602 /* Look in prev_saved_doc_string the same way. */
3603 else if (pos >= prev_saved_doc_string_position
3604 && pos < (prev_saved_doc_string_position
3605 + prev_saved_doc_string_length))
3606 {
3607 saved = prev_saved_doc_string;
3608 saved_position = prev_saved_doc_string_position;
3609 }
3610 if (saved)
3611 {
3612 ptrdiff_t start = pos - saved_position;
3613 ptrdiff_t from, to;
3614
3615 /* Process quoting with ^A,
3616 and find the end of the string,
3617 which is marked with ^_ (037). */
3618 for (from = start, to = start;
3619 saved[from] != 037;)
3620 {
3621 int c = saved[from++];
3622 if (c == 1)
3623 {
3624 c = saved[from++];
3625 saved[to++] = (c == 1 ? c
3626 : c == '0' ? 0
3627 : c == '_' ? 037
3628 : c);
3629 }
3630 else
3631 saved[to++] = c;
3632 }
3633
3634 return make_unibyte_string (saved + start,
3635 to - start);
3636 }
3637 else
3638 return get_doc_string (val, 1, 0);
3639 }
3640
3641 return val;
3642 }
3643 invalid_syntax (". in wrong context");
3644 }
3645 invalid_syntax ("] in a list");
3646 }
3647 tem = Fcons (elt, Qnil);
3648 if (!NILP (tail))
3649 XSETCDR (tail, tem);
3650 else
3651 val = tem;
3652 tail = tem;
3653 }
3654 }
3655 \f
3656 static Lisp_Object initial_obarray;
3657
3658 /* `oblookup' stores the bucket number here, for the sake of Funintern. */
3659
3660 static size_t oblookup_last_bucket_number;
3661
3662 /* Get an error if OBARRAY is not an obarray.
3663 If it is one, return it. */
3664
3665 Lisp_Object
3666 check_obarray (Lisp_Object obarray)
3667 {
3668 if (!VECTORP (obarray) || ASIZE (obarray) == 0)
3669 {
3670 /* If Vobarray is now invalid, force it to be valid. */
3671 if (EQ (Vobarray, obarray)) Vobarray = initial_obarray;
3672 wrong_type_argument (Qvectorp, obarray);
3673 }
3674 return obarray;
3675 }
3676
3677 /* Intern the C string STR: return a symbol with that name,
3678 interned in the current obarray. */
3679
3680 Lisp_Object
3681 intern_1 (const char *str, ptrdiff_t len)
3682 {
3683 Lisp_Object obarray = check_obarray (Vobarray);
3684 Lisp_Object tem = oblookup (obarray, str, len, len);
3685
3686 return SYMBOLP (tem) ? tem : Fintern (make_string (str, len), obarray);
3687 }
3688
3689 Lisp_Object
3690 intern_c_string_1 (const char *str, ptrdiff_t len)
3691 {
3692 Lisp_Object obarray = check_obarray (Vobarray);
3693 Lisp_Object tem = oblookup (obarray, str, len, len);
3694
3695 if (SYMBOLP (tem))
3696 return tem;
3697
3698 if (NILP (Vpurify_flag))
3699 /* Creating a non-pure string from a string literal not
3700 implemented yet. We could just use make_string here and live
3701 with the extra copy. */
3702 emacs_abort ();
3703
3704 return Fintern (make_pure_c_string (str, len), obarray);
3705 }
3706 \f
3707 DEFUN ("intern", Fintern, Sintern, 1, 2, 0,
3708 doc: /* Return the canonical symbol whose name is STRING.
3709 If there is none, one is created by this function and returned.
3710 A second optional argument specifies the obarray to use;
3711 it defaults to the value of `obarray'. */)
3712 (Lisp_Object string, Lisp_Object obarray)
3713 {
3714 register Lisp_Object tem, sym, *ptr;
3715
3716 if (NILP (obarray)) obarray = Vobarray;
3717 obarray = check_obarray (obarray);
3718
3719 CHECK_STRING (string);
3720
3721 tem = oblookup (obarray, SSDATA (string),
3722 SCHARS (string),
3723 SBYTES (string));
3724 if (!INTEGERP (tem))
3725 return tem;
3726
3727 if (!NILP (Vpurify_flag))
3728 string = Fpurecopy (string);
3729 sym = Fmake_symbol (string);
3730
3731 if (EQ (obarray, initial_obarray))
3732 XSYMBOL (sym)->interned = SYMBOL_INTERNED_IN_INITIAL_OBARRAY;
3733 else
3734 XSYMBOL (sym)->interned = SYMBOL_INTERNED;
3735
3736 if ((SREF (string, 0) == ':')
3737 && EQ (obarray, initial_obarray))
3738 {
3739 XSYMBOL (sym)->constant = 1;
3740 XSYMBOL (sym)->redirect = SYMBOL_PLAINVAL;
3741 SET_SYMBOL_VAL (XSYMBOL (sym), sym);
3742 }
3743
3744 ptr = aref_addr (obarray, XINT(tem));
3745 if (SYMBOLP (*ptr))
3746 set_symbol_next (sym, XSYMBOL (*ptr));
3747 else
3748 set_symbol_next (sym, NULL);
3749 *ptr = sym;
3750 return sym;
3751 }
3752
3753 DEFUN ("intern-soft", Fintern_soft, Sintern_soft, 1, 2, 0,
3754 doc: /* Return the canonical symbol named NAME, or nil if none exists.
3755 NAME may be a string or a symbol. If it is a symbol, that exact
3756 symbol is searched for.
3757 A second optional argument specifies the obarray to use;
3758 it defaults to the value of `obarray'. */)
3759 (Lisp_Object name, Lisp_Object obarray)
3760 {
3761 register Lisp_Object tem, string;
3762
3763 if (NILP (obarray)) obarray = Vobarray;
3764 obarray = check_obarray (obarray);
3765
3766 if (!SYMBOLP (name))
3767 {
3768 CHECK_STRING (name);
3769 string = name;
3770 }
3771 else
3772 string = SYMBOL_NAME (name);
3773
3774 tem = oblookup (obarray, SSDATA (string), SCHARS (string), SBYTES (string));
3775 if (INTEGERP (tem) || (SYMBOLP (name) && !EQ (name, tem)))
3776 return Qnil;
3777 else
3778 return tem;
3779 }
3780 \f
3781 DEFUN ("unintern", Funintern, Sunintern, 1, 2, 0,
3782 doc: /* Delete the symbol named NAME, if any, from OBARRAY.
3783 The value is t if a symbol was found and deleted, nil otherwise.
3784 NAME may be a string or a symbol. If it is a symbol, that symbol
3785 is deleted, if it belongs to OBARRAY--no other symbol is deleted.
3786 OBARRAY defaults to the value of the variable `obarray'. */)
3787 (Lisp_Object name, Lisp_Object obarray)
3788 {
3789 register Lisp_Object string, tem;
3790 size_t hash;
3791
3792 if (NILP (obarray)) obarray = Vobarray;
3793 obarray = check_obarray (obarray);
3794
3795 if (SYMBOLP (name))
3796 string = SYMBOL_NAME (name);
3797 else
3798 {
3799 CHECK_STRING (name);
3800 string = name;
3801 }
3802
3803 tem = oblookup (obarray, SSDATA (string),
3804 SCHARS (string),
3805 SBYTES (string));
3806 if (INTEGERP (tem))
3807 return Qnil;
3808 /* If arg was a symbol, don't delete anything but that symbol itself. */
3809 if (SYMBOLP (name) && !EQ (name, tem))
3810 return Qnil;
3811
3812 /* There are plenty of other symbols which will screw up the Emacs
3813 session if we unintern them, as well as even more ways to use
3814 `setq' or `fset' or whatnot to make the Emacs session
3815 unusable. Let's not go down this silly road. --Stef */
3816 /* if (EQ (tem, Qnil) || EQ (tem, Qt))
3817 error ("Attempt to unintern t or nil"); */
3818
3819 XSYMBOL (tem)->interned = SYMBOL_UNINTERNED;
3820
3821 hash = oblookup_last_bucket_number;
3822
3823 if (EQ (AREF (obarray, hash), tem))
3824 {
3825 if (XSYMBOL (tem)->next)
3826 {
3827 Lisp_Object sym;
3828 XSETSYMBOL (sym, XSYMBOL (tem)->next);
3829 ASET (obarray, hash, sym);
3830 }
3831 else
3832 ASET (obarray, hash, make_number (0));
3833 }
3834 else
3835 {
3836 Lisp_Object tail, following;
3837
3838 for (tail = AREF (obarray, hash);
3839 XSYMBOL (tail)->next;
3840 tail = following)
3841 {
3842 XSETSYMBOL (following, XSYMBOL (tail)->next);
3843 if (EQ (following, tem))
3844 {
3845 set_symbol_next (tail, XSYMBOL (following)->next);
3846 break;
3847 }
3848 }
3849 }
3850
3851 return Qt;
3852 }
3853 \f
3854 /* Return the symbol in OBARRAY whose names matches the string
3855 of SIZE characters (SIZE_BYTE bytes) at PTR.
3856 If there is no such symbol in OBARRAY, return nil.
3857
3858 Also store the bucket number in oblookup_last_bucket_number. */
3859
3860 Lisp_Object
3861 oblookup (Lisp_Object obarray, register const char *ptr, ptrdiff_t size, ptrdiff_t size_byte)
3862 {
3863 size_t hash;
3864 size_t obsize;
3865 register Lisp_Object tail;
3866 Lisp_Object bucket, tem;
3867
3868 obarray = check_obarray (obarray);
3869 obsize = ASIZE (obarray);
3870
3871 /* This is sometimes needed in the middle of GC. */
3872 obsize &= ~ARRAY_MARK_FLAG;
3873 hash = hash_string (ptr, size_byte) % obsize;
3874 bucket = AREF (obarray, hash);
3875 oblookup_last_bucket_number = hash;
3876 if (EQ (bucket, make_number (0)))
3877 ;
3878 else if (!SYMBOLP (bucket))
3879 error ("Bad data in guts of obarray"); /* Like CADR error message. */
3880 else
3881 for (tail = bucket; ; XSETSYMBOL (tail, XSYMBOL (tail)->next))
3882 {
3883 if (SBYTES (SYMBOL_NAME (tail)) == size_byte
3884 && SCHARS (SYMBOL_NAME (tail)) == size
3885 && !memcmp (SDATA (SYMBOL_NAME (tail)), ptr, size_byte))
3886 return tail;
3887 else if (XSYMBOL (tail)->next == 0)
3888 break;
3889 }
3890 XSETINT (tem, hash);
3891 return tem;
3892 }
3893 \f
3894 void
3895 map_obarray (Lisp_Object obarray, void (*fn) (Lisp_Object, Lisp_Object), Lisp_Object arg)
3896 {
3897 ptrdiff_t i;
3898 register Lisp_Object tail;
3899 CHECK_VECTOR (obarray);
3900 for (i = ASIZE (obarray) - 1; i >= 0; i--)
3901 {
3902 tail = AREF (obarray, i);
3903 if (SYMBOLP (tail))
3904 while (1)
3905 {
3906 (*fn) (tail, arg);
3907 if (XSYMBOL (tail)->next == 0)
3908 break;
3909 XSETSYMBOL (tail, XSYMBOL (tail)->next);
3910 }
3911 }
3912 }
3913
3914 static void
3915 mapatoms_1 (Lisp_Object sym, Lisp_Object function)
3916 {
3917 call1 (function, sym);
3918 }
3919
3920 DEFUN ("mapatoms", Fmapatoms, Smapatoms, 1, 2, 0,
3921 doc: /* Call FUNCTION on every symbol in OBARRAY.
3922 OBARRAY defaults to the value of `obarray'. */)
3923 (Lisp_Object function, Lisp_Object obarray)
3924 {
3925 if (NILP (obarray)) obarray = Vobarray;
3926 obarray = check_obarray (obarray);
3927
3928 map_obarray (obarray, mapatoms_1, function);
3929 return Qnil;
3930 }
3931
3932 #define OBARRAY_SIZE 1511
3933
3934 void
3935 init_obarray (void)
3936 {
3937 Lisp_Object oblength;
3938 ptrdiff_t size = 100 + MAX_MULTIBYTE_LENGTH;
3939
3940 XSETFASTINT (oblength, OBARRAY_SIZE);
3941
3942 Vobarray = Fmake_vector (oblength, make_number (0));
3943 initial_obarray = Vobarray;
3944 staticpro (&initial_obarray);
3945
3946 Qunbound = Fmake_symbol (build_pure_c_string ("unbound"));
3947 /* Set temporary dummy values to Qnil and Vpurify_flag to satisfy the
3948 NILP (Vpurify_flag) check in intern_c_string. */
3949 Qnil = make_number (-1); Vpurify_flag = make_number (1);
3950 Qnil = intern_c_string ("nil");
3951
3952 /* Fmake_symbol inits fields of new symbols with Qunbound and Qnil,
3953 so those two need to be fixed manually. */
3954 SET_SYMBOL_VAL (XSYMBOL (Qunbound), Qunbound);
3955 set_symbol_function (Qunbound, Qnil);
3956 set_symbol_plist (Qunbound, Qnil);
3957 SET_SYMBOL_VAL (XSYMBOL (Qnil), Qnil);
3958 XSYMBOL (Qnil)->constant = 1;
3959 XSYMBOL (Qnil)->declared_special = 1;
3960 set_symbol_plist (Qnil, Qnil);
3961 set_symbol_function (Qnil, Qnil);
3962
3963 Qt = intern_c_string ("t");
3964 SET_SYMBOL_VAL (XSYMBOL (Qt), Qt);
3965 XSYMBOL (Qnil)->declared_special = 1;
3966 XSYMBOL (Qt)->constant = 1;
3967
3968 /* Qt is correct even if CANNOT_DUMP. loadup.el will set to nil at end. */
3969 Vpurify_flag = Qt;
3970
3971 DEFSYM (Qvariable_documentation, "variable-documentation");
3972
3973 read_buffer = xmalloc (size);
3974 read_buffer_size = size;
3975 }
3976 \f
3977 void
3978 defsubr (struct Lisp_Subr *sname)
3979 {
3980 Lisp_Object sym, tem;
3981 sym = intern_c_string (sname->symbol_name);
3982 XSETPVECTYPE (sname, PVEC_SUBR);
3983 XSETSUBR (tem, sname);
3984 set_symbol_function (sym, tem);
3985 }
3986
3987 #ifdef NOTDEF /* Use fset in subr.el now! */
3988 void
3989 defalias (struct Lisp_Subr *sname, char *string)
3990 {
3991 Lisp_Object sym;
3992 sym = intern (string);
3993 XSETSUBR (XSYMBOL (sym)->function, sname);
3994 }
3995 #endif /* NOTDEF */
3996
3997 /* Define an "integer variable"; a symbol whose value is forwarded to a
3998 C variable of type EMACS_INT. Sample call (with "xx" to fool make-docfile):
3999 DEFxxVAR_INT ("emacs-priority", &emacs_priority, "Documentation"); */
4000 void
4001 defvar_int (struct Lisp_Intfwd *i_fwd,
4002 const char *namestring, EMACS_INT *address)
4003 {
4004 Lisp_Object sym;
4005 sym = intern_c_string (namestring);
4006 i_fwd->type = Lisp_Fwd_Int;
4007 i_fwd->intvar = address;
4008 XSYMBOL (sym)->declared_special = 1;
4009 XSYMBOL (sym)->redirect = SYMBOL_FORWARDED;
4010 SET_SYMBOL_FWD (XSYMBOL (sym), (union Lisp_Fwd *)i_fwd);
4011 }
4012
4013 /* Similar but define a variable whose value is t if address contains 1,
4014 nil if address contains 0. */
4015 void
4016 defvar_bool (struct Lisp_Boolfwd *b_fwd,
4017 const char *namestring, bool *address)
4018 {
4019 Lisp_Object sym;
4020 sym = intern_c_string (namestring);
4021 b_fwd->type = Lisp_Fwd_Bool;
4022 b_fwd->boolvar = address;
4023 XSYMBOL (sym)->declared_special = 1;
4024 XSYMBOL (sym)->redirect = SYMBOL_FORWARDED;
4025 SET_SYMBOL_FWD (XSYMBOL (sym), (union Lisp_Fwd *)b_fwd);
4026 Vbyte_boolean_vars = Fcons (sym, Vbyte_boolean_vars);
4027 }
4028
4029 /* Similar but define a variable whose value is the Lisp Object stored
4030 at address. Two versions: with and without gc-marking of the C
4031 variable. The nopro version is used when that variable will be
4032 gc-marked for some other reason, since marking the same slot twice
4033 can cause trouble with strings. */
4034 void
4035 defvar_lisp_nopro (struct Lisp_Objfwd *o_fwd,
4036 const char *namestring, Lisp_Object *address)
4037 {
4038 Lisp_Object sym;
4039 sym = intern_c_string (namestring);
4040 o_fwd->type = Lisp_Fwd_Obj;
4041 o_fwd->objvar = address;
4042 XSYMBOL (sym)->declared_special = 1;
4043 XSYMBOL (sym)->redirect = SYMBOL_FORWARDED;
4044 SET_SYMBOL_FWD (XSYMBOL (sym), (union Lisp_Fwd *)o_fwd);
4045 }
4046
4047 void
4048 defvar_lisp (struct Lisp_Objfwd *o_fwd,
4049 const char *namestring, Lisp_Object *address)
4050 {
4051 defvar_lisp_nopro (o_fwd, namestring, address);
4052 staticpro (address);
4053 }
4054
4055 /* Similar but define a variable whose value is the Lisp Object stored
4056 at a particular offset in the current kboard object. */
4057
4058 void
4059 defvar_kboard (struct Lisp_Kboard_Objfwd *ko_fwd,
4060 const char *namestring, int offset)
4061 {
4062 Lisp_Object sym;
4063 sym = intern_c_string (namestring);
4064 ko_fwd->type = Lisp_Fwd_Kboard_Obj;
4065 ko_fwd->offset = offset;
4066 XSYMBOL (sym)->declared_special = 1;
4067 XSYMBOL (sym)->redirect = SYMBOL_FORWARDED;
4068 SET_SYMBOL_FWD (XSYMBOL (sym), (union Lisp_Fwd *)ko_fwd);
4069 }
4070 \f
4071 /* Check that the elements of Vload_path exist. */
4072
4073 static void
4074 load_path_check (void)
4075 {
4076 Lisp_Object path_tail;
4077
4078 /* The only elements that might not exist are those from
4079 PATH_LOADSEARCH, EMACSLOADPATH. Anything else is only added if
4080 it exists. */
4081 for (path_tail = Vload_path; !NILP (path_tail); path_tail = XCDR (path_tail))
4082 {
4083 Lisp_Object dirfile;
4084 dirfile = Fcar (path_tail);
4085 if (STRINGP (dirfile))
4086 {
4087 dirfile = Fdirectory_file_name (dirfile);
4088 if (! file_accessible_directory_p (SSDATA (dirfile)))
4089 dir_warning ("Lisp directory", XCAR (path_tail));
4090 }
4091 }
4092 }
4093
4094 /* Record the value of load-path used at the start of dumping
4095 so we can see if the site changed it later during dumping. */
4096 static Lisp_Object dump_path;
4097
4098 /* Compute the default Vload_path, with the following logic:
4099 If CANNOT_DUMP:
4100 use EMACSLOADPATH env-var if set; otherwise use PATH_LOADSEARCH,
4101 prepending PATH_SITELOADSEARCH unless --no-site-lisp.
4102 The remainder is what happens when dumping works:
4103 If purify-flag (ie dumping) just use PATH_DUMPLOADSEARCH.
4104 Otherwise use EMACSLOADPATH if set, else PATH_LOADSEARCH.
4105
4106 If !initialized, then just set both Vload_path and dump_path.
4107 If initialized, then if Vload_path != dump_path, do nothing.
4108 (Presumably the load-path has already been changed by something.
4109 This can only be from a site-load file during dumping,
4110 or because EMACSLOADPATH is set.)
4111 If Vinstallation_directory is not nil (ie, running uninstalled):
4112 If installation-dir/lisp exists and not already a member,
4113 we must be running uninstalled. Reset the load-path
4114 to just installation-dir/lisp. (The default PATH_LOADSEARCH
4115 refers to the eventual installation directories. Since we
4116 are not yet installed, we should not use them, even if they exist.)
4117 If installation-dir/lisp does not exist, just add dump_path at the
4118 end instead.
4119 Add installation-dir/leim (if exists and not already a member) at the front.
4120 Add installation-dir/site-lisp (if !no_site_lisp, and exists
4121 and not already a member) at the front.
4122 If installation-dir != source-dir (ie running an uninstalled,
4123 out-of-tree build) AND install-dir/src/Makefile exists BUT
4124 install-dir/src/Makefile.in does NOT exist (this is a sanity
4125 check), then repeat the above steps for source-dir/lisp,
4126 leim and site-lisp.
4127 Finally, add the site-lisp directories at the front (if !no_site_lisp).
4128 */
4129
4130 void
4131 init_lread (void)
4132 {
4133 const char *normal;
4134
4135 #ifdef CANNOT_DUMP
4136 #ifdef HAVE_NS
4137 const char *loadpath = ns_load_path ();
4138 #endif
4139
4140 normal = PATH_LOADSEARCH;
4141 #ifdef HAVE_NS
4142 Vload_path = decode_env_path ("EMACSLOADPATH", loadpath ? loadpath : normal);
4143 #else
4144 Vload_path = decode_env_path ("EMACSLOADPATH", normal);
4145 #endif
4146
4147 load_path_check ();
4148
4149 /* FIXME CANNOT_DUMP platforms should get source-dir/lisp etc added
4150 to their load-path too, AFAICS. I don't think we can tell the
4151 difference between initialized and !initialized in this case,
4152 so we'll have to do it unconditionally when Vinstallation_directory
4153 is non-nil. */
4154 if (!no_site_lisp && !egetenv ("EMACSLOADPATH"))
4155 {
4156 Lisp_Object sitelisp;
4157 sitelisp = decode_env_path (0, PATH_SITELOADSEARCH);
4158 if (! NILP (sitelisp)) Vload_path = nconc2 (sitelisp, Vload_path);
4159 }
4160 #else /* !CANNOT_DUMP */
4161 if (NILP (Vpurify_flag))
4162 {
4163 normal = PATH_LOADSEARCH;
4164 /* If the EMACSLOADPATH environment variable is set, use its value.
4165 This doesn't apply if we're dumping. */
4166 if (egetenv ("EMACSLOADPATH"))
4167 Vload_path = decode_env_path ("EMACSLOADPATH", normal);
4168 }
4169 else
4170 normal = PATH_DUMPLOADSEARCH;
4171
4172 /* In a dumped Emacs, we normally reset the value of Vload_path using
4173 PATH_LOADSEARCH, since the value that was dumped uses lisp/ in
4174 the source directory, instead of the path of the installed elisp
4175 libraries. However, if it appears that Vload_path has already been
4176 changed from the default that was saved before dumping, don't
4177 change it further. Changes can only be due to EMACSLOADPATH, or
4178 site-lisp files that were processed during dumping. */
4179 if (initialized)
4180 {
4181 if (NILP (Fequal (dump_path, Vload_path)))
4182 {
4183 /* Do not make any changes, just check the elements exist. */
4184 /* Note: --no-site-lisp is ignored.
4185 I don't know what to do about this. */
4186 load_path_check ();
4187 }
4188 else
4189 {
4190 #ifdef HAVE_NS
4191 const char *loadpath = ns_load_path ();
4192 Vload_path = decode_env_path (0, loadpath ? loadpath : normal);
4193 #else
4194 Vload_path = decode_env_path (0, normal);
4195 #endif
4196 if (!NILP (Vinstallation_directory))
4197 {
4198 Lisp_Object tem, tem1;
4199
4200 /* Add to the path the lisp subdir of the installation
4201 dir, if it is accessible. Note: in out-of-tree builds,
4202 this directory is empty save for Makefile. */
4203 tem = Fexpand_file_name (build_string ("lisp"),
4204 Vinstallation_directory);
4205 tem1 = Ffile_accessible_directory_p (tem);
4206 if (!NILP (tem1))
4207 {
4208 if (NILP (Fmember (tem, Vload_path)))
4209 {
4210 /* We are running uninstalled. The default load-path
4211 points to the eventual installed lisp, leim
4212 directories. We should not use those now, even
4213 if they exist, so start over from a clean slate. */
4214 Vload_path = Fcons (tem, Qnil);
4215 }
4216 }
4217 else
4218 /* That dir doesn't exist, so add the build-time
4219 Lisp dirs instead. */
4220 Vload_path = nconc2 (Vload_path, dump_path);
4221
4222 /* Add leim under the installation dir, if it is accessible. */
4223 tem = Fexpand_file_name (build_string ("leim"),
4224 Vinstallation_directory);
4225 tem1 = Ffile_accessible_directory_p (tem);
4226 if (!NILP (tem1))
4227 {
4228 if (NILP (Fmember (tem, Vload_path)))
4229 Vload_path = Fcons (tem, Vload_path);
4230 }
4231
4232 /* Add site-lisp under the installation dir, if it exists. */
4233 if (!no_site_lisp)
4234 {
4235 tem = Fexpand_file_name (build_string ("site-lisp"),
4236 Vinstallation_directory);
4237 tem1 = Ffile_accessible_directory_p (tem);
4238 if (!NILP (tem1))
4239 {
4240 if (NILP (Fmember (tem, Vload_path)))
4241 Vload_path = Fcons (tem, Vload_path);
4242 }
4243 }
4244
4245 /* If Emacs was not built in the source directory,
4246 and it is run from where it was built, add to load-path
4247 the lisp, leim and site-lisp dirs under that directory. */
4248
4249 if (NILP (Fequal (Vinstallation_directory, Vsource_directory)))
4250 {
4251 Lisp_Object tem2;
4252
4253 tem = Fexpand_file_name (build_string ("src/Makefile"),
4254 Vinstallation_directory);
4255 tem1 = Ffile_exists_p (tem);
4256
4257 /* Don't be fooled if they moved the entire source tree
4258 AFTER dumping Emacs. If the build directory is indeed
4259 different from the source dir, src/Makefile.in and
4260 src/Makefile will not be found together. */
4261 tem = Fexpand_file_name (build_string ("src/Makefile.in"),
4262 Vinstallation_directory);
4263 tem2 = Ffile_exists_p (tem);
4264 if (!NILP (tem1) && NILP (tem2))
4265 {
4266 tem = Fexpand_file_name (build_string ("lisp"),
4267 Vsource_directory);
4268
4269 if (NILP (Fmember (tem, Vload_path)))
4270 Vload_path = Fcons (tem, Vload_path);
4271
4272 tem = Fexpand_file_name (build_string ("leim"),
4273 Vsource_directory);
4274
4275 if (NILP (Fmember (tem, Vload_path)))
4276 Vload_path = Fcons (tem, Vload_path);
4277
4278 if (!no_site_lisp)
4279 {
4280 tem = Fexpand_file_name (build_string ("site-lisp"),
4281 Vsource_directory);
4282 tem1 = Ffile_accessible_directory_p (tem);
4283 if (!NILP (tem1))
4284 {
4285 if (NILP (Fmember (tem, Vload_path)))
4286 Vload_path = Fcons (tem, Vload_path);
4287 }
4288 }
4289 }
4290 } /* Vinstallation_directory != Vsource_directory */
4291
4292 } /* if Vinstallation_directory */
4293
4294 /* Check before adding the site-lisp directories.
4295 The install should have created them, but they are not
4296 required, so no need to warn if they are absent.
4297 Or we might be running before installation. */
4298 load_path_check ();
4299
4300 /* Add the site-lisp directories at the front. */
4301 if (!no_site_lisp)
4302 {
4303 Lisp_Object sitelisp;
4304 sitelisp = decode_env_path (0, PATH_SITELOADSEARCH);
4305 if (! NILP (sitelisp)) Vload_path = nconc2 (sitelisp, Vload_path);
4306 }
4307 } /* if dump_path == Vload_path */
4308 }
4309 else /* !initialized */
4310 {
4311 /* NORMAL refers to PATH_DUMPLOADSEARCH, ie the lisp dir in the
4312 source directory. We used to add ../lisp (ie the lisp dir in
4313 the build directory) at the front here, but that caused trouble
4314 because it was copied from dump_path into Vload_path, above,
4315 when Vinstallation_directory was non-nil. It should not be
4316 necessary, since in out of tree builds lisp/ is empty, save
4317 for Makefile. */
4318 Vload_path = decode_env_path (0, normal);
4319 dump_path = Vload_path;
4320 /* No point calling load_path_check; load-path only contains essential
4321 elements from the source directory at this point. They cannot
4322 be missing unless something went extremely (and improbably)
4323 wrong, in which case the build will fail in obvious ways. */
4324 }
4325 #endif /* !CANNOT_DUMP */
4326
4327 Vvalues = Qnil;
4328
4329 load_in_progress = 0;
4330 Vload_file_name = Qnil;
4331
4332 load_descriptor_list = Qnil;
4333
4334 Vstandard_input = Qt;
4335 Vloads_in_progress = Qnil;
4336 }
4337
4338 /* Print a warning that directory intended for use USE and with name
4339 DIRNAME cannot be accessed. On entry, errno should correspond to
4340 the access failure. Print the warning on stderr and put it in
4341 *Messages*. */
4342
4343 void
4344 dir_warning (char const *use, Lisp_Object dirname)
4345 {
4346 static char const format[] = "Warning: %s `%s': %s\n";
4347 int access_errno = errno;
4348 fprintf (stderr, format, use, SSDATA (dirname), strerror (access_errno));
4349
4350 /* Don't log the warning before we've initialized!! */
4351 if (initialized)
4352 {
4353 char const *diagnostic = emacs_strerror (access_errno);
4354 USE_SAFE_ALLOCA;
4355 char *buffer = SAFE_ALLOCA (sizeof format - 3 * (sizeof "%s" - 1)
4356 + strlen (use) + SBYTES (dirname)
4357 + strlen (diagnostic));
4358 ptrdiff_t message_len = esprintf (buffer, format, use, SSDATA (dirname),
4359 diagnostic);
4360 message_dolog (buffer, message_len, 0, STRING_MULTIBYTE (dirname));
4361 SAFE_FREE ();
4362 }
4363 }
4364
4365 void
4366 syms_of_lread (void)
4367 {
4368 defsubr (&Sread);
4369 defsubr (&Sread_from_string);
4370 defsubr (&Sintern);
4371 defsubr (&Sintern_soft);
4372 defsubr (&Sunintern);
4373 defsubr (&Sget_load_suffixes);
4374 defsubr (&Sload);
4375 defsubr (&Seval_buffer);
4376 defsubr (&Seval_region);
4377 defsubr (&Sread_char);
4378 defsubr (&Sread_char_exclusive);
4379 defsubr (&Sread_event);
4380 defsubr (&Sget_file_char);
4381 defsubr (&Smapatoms);
4382 defsubr (&Slocate_file_internal);
4383
4384 DEFVAR_LISP ("obarray", Vobarray,
4385 doc: /* Symbol table for use by `intern' and `read'.
4386 It is a vector whose length ought to be prime for best results.
4387 The vector's contents don't make sense if examined from Lisp programs;
4388 to find all the symbols in an obarray, use `mapatoms'. */);
4389
4390 DEFVAR_LISP ("values", Vvalues,
4391 doc: /* List of values of all expressions which were read, evaluated and printed.
4392 Order is reverse chronological. */);
4393 XSYMBOL (intern ("values"))->declared_special = 0;
4394
4395 DEFVAR_LISP ("standard-input", Vstandard_input,
4396 doc: /* Stream for read to get input from.
4397 See documentation of `read' for possible values. */);
4398 Vstandard_input = Qt;
4399
4400 DEFVAR_LISP ("read-with-symbol-positions", Vread_with_symbol_positions,
4401 doc: /* If non-nil, add position of read symbols to `read-symbol-positions-list'.
4402
4403 If this variable is a buffer, then only forms read from that buffer
4404 will be added to `read-symbol-positions-list'.
4405 If this variable is t, then all read forms will be added.
4406 The effect of all other values other than nil are not currently
4407 defined, although they may be in the future.
4408
4409 The positions are relative to the last call to `read' or
4410 `read-from-string'. It is probably a bad idea to set this variable at
4411 the toplevel; bind it instead. */);
4412 Vread_with_symbol_positions = Qnil;
4413
4414 DEFVAR_LISP ("read-symbol-positions-list", Vread_symbol_positions_list,
4415 doc: /* A list mapping read symbols to their positions.
4416 This variable is modified during calls to `read' or
4417 `read-from-string', but only when `read-with-symbol-positions' is
4418 non-nil.
4419
4420 Each element of the list looks like (SYMBOL . CHAR-POSITION), where
4421 CHAR-POSITION is an integer giving the offset of that occurrence of the
4422 symbol from the position where `read' or `read-from-string' started.
4423
4424 Note that a symbol will appear multiple times in this list, if it was
4425 read multiple times. The list is in the same order as the symbols
4426 were read in. */);
4427 Vread_symbol_positions_list = Qnil;
4428
4429 DEFVAR_LISP ("read-circle", Vread_circle,
4430 doc: /* Non-nil means read recursive structures using #N= and #N# syntax. */);
4431 Vread_circle = Qt;
4432
4433 DEFVAR_LISP ("load-path", Vload_path,
4434 doc: /* List of directories to search for files to load.
4435 Each element is a string (directory name) or nil (try default directory).
4436 Initialized based on EMACSLOADPATH environment variable, if any,
4437 otherwise to default specified by file `epaths.h' when Emacs was built. */);
4438
4439 DEFVAR_LISP ("load-suffixes", Vload_suffixes,
4440 doc: /* List of suffixes for (compiled or source) Emacs Lisp files.
4441 This list should not include the empty string.
4442 `load' and related functions try to append these suffixes, in order,
4443 to the specified file name if a Lisp suffix is allowed or required. */);
4444 Vload_suffixes = Fcons (build_pure_c_string (".elc"),
4445 Fcons (build_pure_c_string (".el"), Qnil));
4446 DEFVAR_LISP ("load-file-rep-suffixes", Vload_file_rep_suffixes,
4447 doc: /* List of suffixes that indicate representations of \
4448 the same file.
4449 This list should normally start with the empty string.
4450
4451 Enabling Auto Compression mode appends the suffixes in
4452 `jka-compr-load-suffixes' to this list and disabling Auto Compression
4453 mode removes them again. `load' and related functions use this list to
4454 determine whether they should look for compressed versions of a file
4455 and, if so, which suffixes they should try to append to the file name
4456 in order to do so. However, if you want to customize which suffixes
4457 the loading functions recognize as compression suffixes, you should
4458 customize `jka-compr-load-suffixes' rather than the present variable. */);
4459 Vload_file_rep_suffixes = Fcons (empty_unibyte_string, Qnil);
4460
4461 DEFVAR_BOOL ("load-in-progress", load_in_progress,
4462 doc: /* Non-nil if inside of `load'. */);
4463 DEFSYM (Qload_in_progress, "load-in-progress");
4464
4465 DEFVAR_LISP ("after-load-alist", Vafter_load_alist,
4466 doc: /* An alist of expressions to be evalled when particular files are loaded.
4467 Each element looks like (REGEXP-OR-FEATURE FORMS...).
4468
4469 REGEXP-OR-FEATURE is either a regular expression to match file names, or
4470 a symbol \(a feature name).
4471
4472 When `load' is run and the file-name argument matches an element's
4473 REGEXP-OR-FEATURE, or when `provide' is run and provides the symbol
4474 REGEXP-OR-FEATURE, the FORMS in the element are executed.
4475
4476 An error in FORMS does not undo the load, but does prevent execution of
4477 the rest of the FORMS. */);
4478 Vafter_load_alist = Qnil;
4479
4480 DEFVAR_LISP ("load-history", Vload_history,
4481 doc: /* Alist mapping loaded file names to symbols and features.
4482 Each alist element should be a list (FILE-NAME ENTRIES...), where
4483 FILE-NAME is the name of a file that has been loaded into Emacs.
4484 The file name is absolute and true (i.e. it doesn't contain symlinks).
4485 As an exception, one of the alist elements may have FILE-NAME nil,
4486 for symbols and features not associated with any file.
4487
4488 The remaining ENTRIES in the alist element describe the functions and
4489 variables defined in that file, the features provided, and the
4490 features required. Each entry has the form `(provide . FEATURE)',
4491 `(require . FEATURE)', `(defun . FUNCTION)', `(autoload . SYMBOL)',
4492 `(defface . SYMBOL)', or `(t . SYMBOL)'. Entries like `(t . SYMBOL)'
4493 may precede a `(defun . FUNCTION)' entry, and means that SYMBOL was an
4494 autoload before this file redefined it as a function. In addition,
4495 entries may also be single symbols, which means that SYMBOL was
4496 defined by `defvar' or `defconst'.
4497
4498 During preloading, the file name recorded is relative to the main Lisp
4499 directory. These file names are converted to absolute at startup. */);
4500 Vload_history = Qnil;
4501
4502 DEFVAR_LISP ("load-file-name", Vload_file_name,
4503 doc: /* Full name of file being loaded by `load'. */);
4504 Vload_file_name = Qnil;
4505
4506 DEFVAR_LISP ("user-init-file", Vuser_init_file,
4507 doc: /* File name, including directory, of user's initialization file.
4508 If the file loaded had extension `.elc', and the corresponding source file
4509 exists, this variable contains the name of source file, suitable for use
4510 by functions like `custom-save-all' which edit the init file.
4511 While Emacs loads and evaluates the init file, value is the real name
4512 of the file, regardless of whether or not it has the `.elc' extension. */);
4513 Vuser_init_file = Qnil;
4514
4515 DEFVAR_LISP ("current-load-list", Vcurrent_load_list,
4516 doc: /* Used for internal purposes by `load'. */);
4517 Vcurrent_load_list = Qnil;
4518
4519 DEFVAR_LISP ("load-read-function", Vload_read_function,
4520 doc: /* Function used by `load' and `eval-region' for reading expressions.
4521 The default is nil, which means use the function `read'. */);
4522 Vload_read_function = Qnil;
4523
4524 DEFVAR_LISP ("load-source-file-function", Vload_source_file_function,
4525 doc: /* Function called in `load' to load an Emacs Lisp source file.
4526 The value should be a function for doing code conversion before
4527 reading a source file. It can also be nil, in which case loading is
4528 done without any code conversion.
4529
4530 If the value is a function, it is called with four arguments,
4531 FULLNAME, FILE, NOERROR, NOMESSAGE. FULLNAME is the absolute name of
4532 the file to load, FILE is the non-absolute name (for messages etc.),
4533 and NOERROR and NOMESSAGE are the corresponding arguments passed to
4534 `load'. The function should return t if the file was loaded. */);
4535 Vload_source_file_function = Qnil;
4536
4537 DEFVAR_BOOL ("load-force-doc-strings", load_force_doc_strings,
4538 doc: /* Non-nil means `load' should force-load all dynamic doc strings.
4539 This is useful when the file being loaded is a temporary copy. */);
4540 load_force_doc_strings = 0;
4541
4542 DEFVAR_BOOL ("load-convert-to-unibyte", load_convert_to_unibyte,
4543 doc: /* Non-nil means `read' converts strings to unibyte whenever possible.
4544 This is normally bound by `load' and `eval-buffer' to control `read',
4545 and is not meant for users to change. */);
4546 load_convert_to_unibyte = 0;
4547
4548 DEFVAR_LISP ("source-directory", Vsource_directory,
4549 doc: /* Directory in which Emacs sources were found when Emacs was built.
4550 You cannot count on them to still be there! */);
4551 Vsource_directory
4552 = Fexpand_file_name (build_string ("../"),
4553 Fcar (decode_env_path (0, PATH_DUMPLOADSEARCH)));
4554
4555 DEFVAR_LISP ("preloaded-file-list", Vpreloaded_file_list,
4556 doc: /* List of files that were preloaded (when dumping Emacs). */);
4557 Vpreloaded_file_list = Qnil;
4558
4559 DEFVAR_LISP ("byte-boolean-vars", Vbyte_boolean_vars,
4560 doc: /* List of all DEFVAR_BOOL variables, used by the byte code optimizer. */);
4561 Vbyte_boolean_vars = Qnil;
4562
4563 DEFVAR_BOOL ("load-dangerous-libraries", load_dangerous_libraries,
4564 doc: /* Non-nil means load dangerous compiled Lisp files.
4565 Some versions of XEmacs use different byte codes than Emacs. These
4566 incompatible byte codes can make Emacs crash when it tries to execute
4567 them. */);
4568 load_dangerous_libraries = 0;
4569
4570 DEFVAR_BOOL ("force-load-messages", force_load_messages,
4571 doc: /* Non-nil means force printing messages when loading Lisp files.
4572 This overrides the value of the NOMESSAGE argument to `load'. */);
4573 force_load_messages = 0;
4574
4575 DEFVAR_LISP ("bytecomp-version-regexp", Vbytecomp_version_regexp,
4576 doc: /* Regular expression matching safe to load compiled Lisp files.
4577 When Emacs loads a compiled Lisp file, it reads the first 512 bytes
4578 from the file, and matches them against this regular expression.
4579 When the regular expression matches, the file is considered to be safe
4580 to load. See also `load-dangerous-libraries'. */);
4581 Vbytecomp_version_regexp
4582 = build_pure_c_string ("^;;;.\\(in Emacs version\\|bytecomp version FSF\\)");
4583
4584 DEFSYM (Qlexical_binding, "lexical-binding");
4585 DEFVAR_LISP ("lexical-binding", Vlexical_binding,
4586 doc: /* Whether to use lexical binding when evaluating code.
4587 Non-nil means that the code in the current buffer should be evaluated
4588 with lexical binding.
4589 This variable is automatically set from the file variables of an
4590 interpreted Lisp file read using `load'. Unlike other file local
4591 variables, this must be set in the first line of a file. */);
4592 Vlexical_binding = Qnil;
4593 Fmake_variable_buffer_local (Qlexical_binding);
4594
4595 DEFVAR_LISP ("eval-buffer-list", Veval_buffer_list,
4596 doc: /* List of buffers being read from by calls to `eval-buffer' and `eval-region'. */);
4597 Veval_buffer_list = Qnil;
4598
4599 DEFVAR_LISP ("old-style-backquotes", Vold_style_backquotes,
4600 doc: /* Set to non-nil when `read' encounters an old-style backquote. */);
4601 Vold_style_backquotes = Qnil;
4602 DEFSYM (Qold_style_backquotes, "old-style-backquotes");
4603
4604 /* Vsource_directory was initialized in init_lread. */
4605
4606 load_descriptor_list = Qnil;
4607 staticpro (&load_descriptor_list);
4608
4609 DEFSYM (Qcurrent_load_list, "current-load-list");
4610 DEFSYM (Qstandard_input, "standard-input");
4611 DEFSYM (Qread_char, "read-char");
4612 DEFSYM (Qget_file_char, "get-file-char");
4613 DEFSYM (Qget_emacs_mule_file_char, "get-emacs-mule-file-char");
4614 DEFSYM (Qload_force_doc_strings, "load-force-doc-strings");
4615
4616 DEFSYM (Qbackquote, "`");
4617 DEFSYM (Qcomma, ",");
4618 DEFSYM (Qcomma_at, ",@");
4619 DEFSYM (Qcomma_dot, ",.");
4620
4621 DEFSYM (Qinhibit_file_name_operation, "inhibit-file-name-operation");
4622 DEFSYM (Qascii_character, "ascii-character");
4623 DEFSYM (Qfunction, "function");
4624 DEFSYM (Qload, "load");
4625 DEFSYM (Qload_file_name, "load-file-name");
4626 DEFSYM (Qeval_buffer_list, "eval-buffer-list");
4627 DEFSYM (Qfile_truename, "file-truename");
4628 DEFSYM (Qdir_ok, "dir-ok");
4629 DEFSYM (Qdo_after_load_evaluation, "do-after-load-evaluation");
4630
4631 staticpro (&dump_path);
4632
4633 staticpro (&read_objects);
4634 read_objects = Qnil;
4635 staticpro (&seen_list);
4636 seen_list = Qnil;
4637
4638 Vloads_in_progress = Qnil;
4639 staticpro (&Vloads_in_progress);
4640
4641 DEFSYM (Qhash_table, "hash-table");
4642 DEFSYM (Qdata, "data");
4643 DEFSYM (Qtest, "test");
4644 DEFSYM (Qsize, "size");
4645 DEFSYM (Qweakness, "weakness");
4646 DEFSYM (Qrehash_size, "rehash-size");
4647 DEFSYM (Qrehash_threshold, "rehash-threshold");
4648 }