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