Add full Unicode capability to ports and the default reader
[bpt/guile.git] / libguile / print.c
1 /* Copyright (C) 1995-1999,2000,2001, 2002, 2003, 2004, 2006, 2008, 2009 Free Software Foundation, Inc.
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public License
5 * as published by the Free Software Foundation; either version 3 of
6 * the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
16 * 02110-1301 USA
17 */
18
19
20 \f
21 #ifdef HAVE_CONFIG_H
22 # include <config.h>
23 #endif
24
25 #include <errno.h>
26 #include <uniconv.h>
27 #include <unictype.h>
28
29 #include "libguile/_scm.h"
30 #include "libguile/chars.h"
31 #include "libguile/continuations.h"
32 #include "libguile/smob.h"
33 #include "libguile/eval.h"
34 #include "libguile/macros.h"
35 #include "libguile/procprop.h"
36 #include "libguile/read.h"
37 #include "libguile/weaks.h"
38 #include "libguile/programs.h"
39 #include "libguile/unif.h"
40 #include "libguile/alist.h"
41 #include "libguile/struct.h"
42 #include "libguile/objects.h"
43 #include "libguile/ports.h"
44 #include "libguile/root.h"
45 #include "libguile/strings.h"
46 #include "libguile/strports.h"
47 #include "libguile/vectors.h"
48 #include "libguile/lang.h"
49 #include "libguile/numbers.h"
50
51 #include "libguile/validate.h"
52 #include "libguile/print.h"
53
54 #include "libguile/private-options.h"
55
56 \f
57
58 /* {Names of immediate symbols}
59 *
60 * This table must agree with the declarations in scm.h: {Immediate Symbols}.
61 */
62
63 /* This table must agree with the list of flags in tags.h. */
64 static const char *iflagnames[] =
65 {
66 "#f",
67 "#t",
68 "#<undefined>",
69 "#<eof>",
70 "()",
71 "#<unspecified>",
72
73 /* Unbound slot marker for GOOPS. For internal use in GOOPS only. */
74 "#<unbound>",
75
76 /* Elisp nil value. This is its Scheme name; whenever it's printed in
77 * Elisp, it should appear as the symbol `nil'. */
78 "#nil"
79 };
80
81 SCM_SYMBOL (sym_reader, "reader");
82
83 scm_t_option scm_print_opts[] = {
84 { SCM_OPTION_SCM, "closure-hook", SCM_UNPACK (SCM_BOOL_F),
85 "Hook for printing closures (should handle macros as well)." },
86 { SCM_OPTION_BOOLEAN, "source", 0,
87 "Print closures with source." },
88 { SCM_OPTION_SCM, "highlight-prefix", (unsigned long)SCM_BOOL_F,
89 "The string to print before highlighted values." },
90 { SCM_OPTION_SCM, "highlight-suffix", (unsigned long)SCM_BOOL_F,
91 "The string to print after highlighted values." },
92 { SCM_OPTION_SCM, "quote-keywordish-symbols", (unsigned long)SCM_BOOL_F,
93 "How to print symbols that have a colon as their first or last character. "
94 "The value '#f' does not quote the colons; '#t' quotes them; "
95 "'reader' quotes them when the reader option 'keywords' is not '#f'."
96 },
97 { 0 },
98
99 };
100
101 SCM_DEFINE (scm_print_options, "print-options-interface", 0, 1, 0,
102 (SCM setting),
103 "Option interface for the print options. Instead of using\n"
104 "this procedure directly, use the procedures\n"
105 "@code{print-enable}, @code{print-disable}, @code{print-set!}\n"
106 "and @code{print-options}.")
107 #define FUNC_NAME s_scm_print_options
108 {
109 SCM ans = scm_options (setting,
110 scm_print_opts,
111 FUNC_NAME);
112 return ans;
113 }
114 #undef FUNC_NAME
115
116 \f
117 /* {Printing of Scheme Objects}
118 */
119
120 /* Detection of circular references.
121 *
122 * Due to other constraints in the implementation, this code has bad
123 * time complexity (O (depth * N)), The printer code can be
124 * rewritten to be O(N).
125 */
126 #define PUSH_REF(pstate, obj) \
127 do \
128 { \
129 PSTATE_STACK_SET (pstate, pstate->top, obj); \
130 pstate->top++; \
131 if (pstate->top == pstate->ceiling) \
132 grow_ref_stack (pstate); \
133 } while(0)
134
135 #define ENTER_NESTED_DATA(pstate, obj, label) \
136 do \
137 { \
138 register unsigned long i; \
139 for (i = 0; i < pstate->top; ++i) \
140 if (scm_is_eq (PSTATE_STACK_REF (pstate, i), (obj))) \
141 goto label; \
142 if (pstate->fancyp) \
143 { \
144 if (pstate->top - pstate->list_offset >= pstate->level) \
145 { \
146 scm_putc ('#', port); \
147 return; \
148 } \
149 } \
150 PUSH_REF(pstate, obj); \
151 } while(0)
152
153 #define EXIT_NESTED_DATA(pstate) \
154 do \
155 { \
156 --pstate->top; \
157 PSTATE_STACK_SET (pstate, pstate->top, SCM_UNDEFINED); \
158 } \
159 while (0)
160
161 SCM scm_print_state_vtable = SCM_BOOL_F;
162 static SCM print_state_pool = SCM_EOL;
163 scm_i_pthread_mutex_t print_state_mutex = SCM_I_PTHREAD_MUTEX_INITIALIZER;
164
165 #ifdef GUILE_DEBUG /* Used for debugging purposes */
166
167 SCM_DEFINE (scm_current_pstate, "current-pstate", 0, 0, 0,
168 (),
169 "Return the current-pstate -- the car of the\n"
170 "@code{print_state_pool}. @code{current-pstate} is only\n"
171 "included in @code{--enable-guile-debug} builds.")
172 #define FUNC_NAME s_scm_current_pstate
173 {
174 if (!scm_is_null (print_state_pool))
175 return SCM_CAR (print_state_pool);
176 else
177 return SCM_BOOL_F;
178 }
179 #undef FUNC_NAME
180
181 #endif
182
183 #define PSTATE_SIZE 50L
184
185 static SCM
186 make_print_state (void)
187 {
188 SCM print_state
189 = scm_make_struct (scm_print_state_vtable, SCM_INUM0, SCM_EOL);
190 scm_print_state *pstate = SCM_PRINT_STATE (print_state);
191 pstate->ref_vect = scm_c_make_vector (PSTATE_SIZE, SCM_UNDEFINED);
192 pstate->ceiling = SCM_SIMPLE_VECTOR_LENGTH (pstate->ref_vect);
193 pstate->highlight_objects = SCM_EOL;
194 return print_state;
195 }
196
197 SCM
198 scm_make_print_state ()
199 {
200 SCM answer = SCM_BOOL_F;
201
202 /* First try to allocate a print state from the pool */
203 scm_i_pthread_mutex_lock (&print_state_mutex);
204 if (!scm_is_null (print_state_pool))
205 {
206 answer = SCM_CAR (print_state_pool);
207 print_state_pool = SCM_CDR (print_state_pool);
208 }
209 scm_i_pthread_mutex_unlock (&print_state_mutex);
210
211 return scm_is_false (answer) ? make_print_state () : answer;
212 }
213
214 void
215 scm_free_print_state (SCM print_state)
216 {
217 SCM handle;
218 scm_print_state *pstate = SCM_PRINT_STATE (print_state);
219 /* Cleanup before returning print state to pool.
220 * It is better to do it here. Doing it in scm_prin1
221 * would cost more since that function is called much more
222 * often.
223 */
224 pstate->fancyp = 0;
225 pstate->revealed = 0;
226 pstate->highlight_objects = SCM_EOL;
227 scm_i_pthread_mutex_lock (&print_state_mutex);
228 handle = scm_cons (print_state, print_state_pool);
229 print_state_pool = handle;
230 scm_i_pthread_mutex_unlock (&print_state_mutex);
231 }
232
233 SCM
234 scm_i_port_with_print_state (SCM port, SCM print_state)
235 {
236 if (SCM_UNBNDP (print_state))
237 {
238 if (SCM_PORT_WITH_PS_P (port))
239 return port;
240 else
241 print_state = scm_make_print_state ();
242 /* port does not need to be coerced since it doesn't have ps */
243 }
244 else
245 port = SCM_COERCE_OUTPORT (port);
246 SCM_RETURN_NEWSMOB (scm_tc16_port_with_ps,
247 SCM_UNPACK (scm_cons (port, print_state)));
248 }
249
250 static void
251 grow_ref_stack (scm_print_state *pstate)
252 {
253 SCM old_vect = pstate->ref_vect;
254 size_t old_size = SCM_SIMPLE_VECTOR_LENGTH (old_vect);
255 size_t new_size = 2 * pstate->ceiling;
256 SCM new_vect = scm_c_make_vector (new_size, SCM_UNDEFINED);
257 unsigned long int i;
258
259 for (i = 0; i != old_size; ++i)
260 SCM_SIMPLE_VECTOR_SET (new_vect, i, SCM_SIMPLE_VECTOR_REF (old_vect, i));
261
262 pstate->ref_vect = new_vect;
263 pstate->ceiling = new_size;
264 }
265
266 #define PSTATE_STACK_REF(p,i) SCM_SIMPLE_VECTOR_REF((p)->ref_vect, (i))
267 #define PSTATE_STACK_SET(p,i,v) SCM_SIMPLE_VECTOR_SET((p)->ref_vect, (i), (v))
268
269 static void
270 print_circref (SCM port, scm_print_state *pstate, SCM ref)
271 {
272 register long i;
273 long self = pstate->top - 1;
274 i = pstate->top - 1;
275 if (scm_is_pair (PSTATE_STACK_REF (pstate, i)))
276 {
277 while (i > 0)
278 {
279 if (!scm_is_pair (PSTATE_STACK_REF (pstate, i-1))
280 || !scm_is_eq (SCM_CDR (PSTATE_STACK_REF (pstate, i-1)),
281 SCM_CDR (PSTATE_STACK_REF (pstate, i))))
282 break;
283 --i;
284 }
285 self = i;
286 }
287 for (i = pstate->top - 1; 1; --i)
288 if (scm_is_eq (PSTATE_STACK_REF(pstate, i), ref))
289 break;
290 scm_putc ('#', port);
291 scm_intprint (i - self, 10, port);
292 scm_putc ('#', port);
293 }
294
295 /* Print the name of a symbol. */
296
297 static int
298 quote_keywordish_symbol (SCM symbol)
299 {
300 SCM option;
301
302 if (scm_i_symbol_ref (symbol, 0) != ':'
303 && scm_i_symbol_ref (symbol, scm_i_symbol_length (symbol) - 1) != ':')
304 return 0;
305
306 option = SCM_PRINT_KEYWORD_STYLE;
307 if (scm_is_false (option))
308 return 0;
309 if (scm_is_eq (option, sym_reader))
310 return scm_is_true (SCM_PACK (SCM_KEYWORD_STYLE));
311 return 1;
312 }
313
314 void
315 scm_i_print_symbol_name (SCM str, SCM port)
316 {
317 /* This points to the first character that has not yet been written to the
318 * port. */
319 size_t pos = 0;
320 /* This points to the character we're currently looking at. */
321 size_t end;
322 /* If the name contains weird characters, we'll escape them with
323 * backslashes and set this flag; it indicates that we should surround the
324 * name with "#{" and "}#". */
325 int weird = 0;
326 /* Backslashes are not sufficient to make a name weird, but if a name is
327 * weird because of other characters, backslahes need to be escaped too.
328 * The first time we see a backslash, we set maybe_weird, and mw_pos points
329 * to the backslash. Then if the name turns out to be weird, we re-process
330 * everything starting from mw_pos.
331 * We could instead make backslashes always weird. This is not necessary
332 * to ensure that the output is (read)-able, but it would make this code
333 * simpler and faster. */
334 int maybe_weird = 0;
335 size_t mw_pos = 0;
336 size_t len = scm_i_symbol_length (str);
337 scm_t_wchar str0 = scm_i_symbol_ref (str, 0);
338
339 if (len == 0 || str0 == '\'' || str0 == '`' || str0 == ','
340 || quote_keywordish_symbol (str)
341 || (str0 == '.' && len == 1)
342 || scm_is_true (scm_i_string_to_number (scm_symbol_to_string (str), 10)))
343 {
344 scm_lfwrite ("#{", 2, port);
345 weird = 1;
346 }
347
348 for (end = pos; end < len; ++end)
349 switch (scm_i_symbol_ref (str, end))
350 {
351 #ifdef BRACKETS_AS_PARENS
352 case '[':
353 case ']':
354 #endif
355 case '(':
356 case ')':
357 case '"':
358 case ';':
359 case '#':
360 case SCM_WHITE_SPACES:
361 case SCM_LINE_INCREMENTORS:
362 weird_handler:
363 if (maybe_weird)
364 {
365 end = mw_pos;
366 maybe_weird = 0;
367 }
368 if (!weird)
369 {
370 scm_lfwrite ("#{", 2, port);
371 weird = 1;
372 }
373 if (pos < end)
374 scm_lfwrite_substr (scm_symbol_to_string (str), pos, end, port);
375 {
376 char buf[2];
377 buf[0] = '\\';
378 buf[1] = (char) (unsigned char) scm_i_symbol_ref (str, end);
379 scm_lfwrite (buf, 2, port);
380 }
381 pos = end + 1;
382 break;
383 case '\\':
384 if (weird)
385 goto weird_handler;
386 if (!maybe_weird)
387 {
388 maybe_weird = 1;
389 mw_pos = pos;
390 }
391 break;
392 default:
393 break;
394 }
395 if (pos < end)
396 scm_lfwrite_substr (scm_symbol_to_string (str), pos, end, port);
397 if (weird)
398 scm_lfwrite ("}#", 2, port);
399 }
400
401 void
402 scm_print_symbol_name (const char *str, size_t len, SCM port)
403 {
404 SCM symbol = scm_from_locale_symboln (str, len);
405 return scm_i_print_symbol_name (symbol, port);
406 }
407
408 /* Print generally. Handles both write and display according to PSTATE.
409 */
410 SCM_GPROC(s_write, "write", 1, 1, 0, scm_write, g_write);
411 SCM_GPROC(s_display, "display", 1, 1, 0, scm_display, g_display);
412
413 static void iprin1 (SCM exp, SCM port, scm_print_state *pstate);
414
415 void
416 scm_iprin1 (SCM exp, SCM port, scm_print_state *pstate)
417 {
418 if (pstate->fancyp
419 && scm_is_true (scm_memq (exp, pstate->highlight_objects)))
420 {
421 scm_display (SCM_PRINT_HIGHLIGHT_PREFIX, port);
422 iprin1 (exp, port, pstate);
423 scm_display (SCM_PRINT_HIGHLIGHT_SUFFIX, port);
424 }
425 else
426 iprin1 (exp, port, pstate);
427 }
428
429 static void
430 iprin1 (SCM exp, SCM port, scm_print_state *pstate)
431 {
432 switch (SCM_ITAG3 (exp))
433 {
434 case scm_tc3_closure:
435 case scm_tc3_tc7_1:
436 case scm_tc3_tc7_2:
437 /* These tc3 tags should never occur in an immediate value. They are
438 * only used in cell types of non-immediates, i. e. the value returned
439 * by SCM_CELL_TYPE (exp) can use these tags.
440 */
441 scm_ipruk ("immediate", exp, port);
442 break;
443 case scm_tc3_int_1:
444 case scm_tc3_int_2:
445 scm_intprint (SCM_I_INUM (exp), 10, port);
446 break;
447 case scm_tc3_imm24:
448 if (SCM_CHARP (exp))
449 {
450 scm_t_wchar i = SCM_CHAR (exp);
451 const char *name;
452
453 if (SCM_WRITINGP (pstate))
454 {
455 scm_puts ("#\\", port);
456 name = scm_i_charname (exp);
457 if (name != NULL)
458 scm_puts (name, port);
459 else if (uc_is_general_category_withtable (i, UC_CATEGORY_MASK_L
460 | UC_CATEGORY_MASK_M
461 | UC_CATEGORY_MASK_N
462 | UC_CATEGORY_MASK_P
463 | UC_CATEGORY_MASK_S))
464 /* Print the character if is graphic character. */
465 {
466 scm_t_wchar *wbuf;
467 SCM wstr = scm_i_make_wide_string (1, &wbuf);
468 char *buf;
469 size_t len;
470 const char *enc;
471
472 enc = scm_i_get_port_encoding (port);
473 wbuf[0] = i;
474 if (enc == NULL && i <= 0xFF)
475 {
476 /* Character is graphic and Latin-1. Print it */
477 scm_lfwrite_str (wstr, port);
478 }
479 else
480 {
481 buf = u32_conv_to_encoding (enc,
482 iconveh_error,
483 (scm_t_uint32 *) wbuf,
484 1,
485 NULL,
486 NULL, &len);
487 if (buf != NULL)
488 {
489 /* Character is graphic. Print it. */
490 scm_lfwrite_str (wstr, port);
491 free (buf);
492 }
493 else
494 /* Character is graphic but unrepresentable in
495 this port's encoding. */
496 scm_intprint (i, 8, port);
497 }
498 }
499 else
500 /* Character is a non-graphical character. */
501 scm_intprint (i, 8, port);
502 }
503 else
504 scm_i_charprint (i, port);
505 }
506 else if (SCM_IFLAGP (exp)
507 && ((size_t) SCM_IFLAGNUM (exp) < (sizeof iflagnames / sizeof (char *))))
508 {
509 scm_puts (iflagnames [SCM_IFLAGNUM (exp)], port);
510 }
511 else if (SCM_ISYMP (exp))
512 {
513 scm_i_print_isym (exp, port);
514 }
515 else if (SCM_ILOCP (exp))
516 {
517 scm_i_print_iloc (exp, port);
518 }
519 else
520 {
521 /* unknown immediate value */
522 scm_ipruk ("immediate", exp, port);
523 }
524 break;
525 case scm_tc3_cons:
526 switch (SCM_TYP7 (exp))
527 {
528 case scm_tcs_struct:
529 {
530 ENTER_NESTED_DATA (pstate, exp, circref);
531 if (SCM_OBJ_CLASS_FLAGS (exp) & SCM_CLASSF_GOOPS)
532 {
533 SCM pwps, print = pstate->writingp ? g_write : g_display;
534 if (!print)
535 goto print_struct;
536 pwps = scm_i_port_with_print_state (port, pstate->handle);
537 pstate->revealed = 1;
538 scm_call_generic_2 (print, exp, pwps);
539 }
540 else
541 {
542 print_struct:
543 scm_print_struct (exp, port, pstate);
544 }
545 EXIT_NESTED_DATA (pstate);
546 }
547 break;
548 case scm_tcs_cons_imcar:
549 case scm_tcs_cons_nimcar:
550 ENTER_NESTED_DATA (pstate, exp, circref);
551 scm_iprlist ("(", exp, ')', port, pstate);
552 EXIT_NESTED_DATA (pstate);
553 break;
554 circref:
555 print_circref (port, pstate, exp);
556 break;
557 case scm_tcs_closures:
558 if (scm_is_false (scm_procedure_p (SCM_PRINT_CLOSURE))
559 || scm_is_false (scm_printer_apply (SCM_PRINT_CLOSURE,
560 exp, port, pstate)))
561 {
562 SCM formals = SCM_CLOSURE_FORMALS (exp);
563 scm_puts ("#<procedure", port);
564 scm_putc (' ', port);
565 scm_iprin1 (scm_procedure_name (exp), port, pstate);
566 scm_putc (' ', port);
567 if (SCM_PRINT_SOURCE_P)
568 {
569 SCM env = SCM_ENV (exp);
570 SCM xenv = SCM_EXTEND_ENV (formals, SCM_EOL, env);
571 SCM src = scm_i_unmemocopy_body (SCM_CODE (exp), xenv);
572 ENTER_NESTED_DATA (pstate, exp, circref);
573 scm_iprin1 (src, port, pstate);
574 EXIT_NESTED_DATA (pstate);
575 }
576 else
577 scm_iprin1 (formals, port, pstate);
578 scm_putc ('>', port);
579 }
580 break;
581 case scm_tc7_number:
582 switch SCM_TYP16 (exp) {
583 case scm_tc16_big:
584 scm_bigprint (exp, port, pstate);
585 break;
586 case scm_tc16_real:
587 scm_print_real (exp, port, pstate);
588 break;
589 case scm_tc16_complex:
590 scm_print_complex (exp, port, pstate);
591 break;
592 case scm_tc16_fraction:
593 scm_i_print_fraction (exp, port, pstate);
594 break;
595 }
596 break;
597 case scm_tc7_string:
598 if (SCM_WRITINGP (pstate))
599 {
600 size_t i, j, len;
601 static char const hex[] = "0123456789abcdef";
602 char buf[8];
603
604
605 scm_putc ('"', port);
606 len = scm_i_string_length (exp);
607 for (i = 0; i < len; ++i)
608 {
609 scm_t_wchar ch = scm_i_string_ref (exp, i);
610 int printed = 0;
611
612 if (ch == ' ' || ch == '\n')
613 {
614 scm_putc (ch, port);
615 printed = 1;
616 }
617 else if (ch == '"' || ch == '\\')
618 {
619 scm_putc ('\\', port);
620 scm_i_charprint (ch, port);
621 printed = 1;
622 }
623 else
624 if (uc_is_general_category_withtable
625 (ch,
626 UC_CATEGORY_MASK_L | UC_CATEGORY_MASK_M |
627 UC_CATEGORY_MASK_N | UC_CATEGORY_MASK_P |
628 UC_CATEGORY_MASK_S))
629 {
630 /* Print the character since it is a graphic
631 character. */
632 scm_t_wchar *wbuf;
633 SCM wstr = scm_i_make_wide_string (1, &wbuf);
634 char *buf;
635 size_t len;
636
637 if (scm_i_get_port_encoding (port))
638 {
639 wstr = scm_i_make_wide_string (1, &wbuf);
640 wbuf[0] = ch;
641 buf = u32_conv_to_encoding (scm_i_get_port_encoding (port),
642 iconveh_error,
643 (scm_t_uint32 *) wbuf,
644 1 ,
645 NULL,
646 NULL, &len);
647 if (buf != NULL)
648 {
649 /* Character is graphic and representable in
650 this encoding. Print it. */
651 scm_lfwrite_str (wstr, port);
652 free (buf);
653 printed = 1;
654 }
655 }
656 else
657 if (ch <= 0xFF)
658 {
659 scm_putc (ch, port);
660 printed = 1;
661 }
662 }
663
664 if (!printed)
665 {
666 /* Character is graphic but unrepresentable in
667 this port's encoding or is not graphic. */
668 if (ch <= 0xFF)
669 {
670 buf[0] = '\\';
671 buf[1] = 'x';
672 buf[2] = hex[ch / 16];
673 buf[3] = hex[ch % 16];
674 scm_lfwrite (buf, 4, port);
675 }
676 else if (ch <= 0xFFFF)
677 {
678 buf[0] = '\\';
679 buf[1] = 'u';
680 buf[2] = hex[(ch & 0xF000) >> 12];
681 buf[3] = hex[(ch & 0xF00) >> 8];
682 buf[4] = hex[(ch & 0xF0) >> 4];
683 buf[5] = hex[(ch & 0xF)];
684 scm_lfwrite (buf, 6, port);
685 j = i + 1;
686 }
687 else if (ch > 0xFFFF)
688 {
689 buf[0] = '\\';
690 buf[1] = 'U';
691 buf[2] = hex[(ch & 0xF00000) >> 20];
692 buf[3] = hex[(ch & 0xF0000) >> 16];
693 buf[4] = hex[(ch & 0xF000) >> 12];
694 buf[5] = hex[(ch & 0xF00) >> 8];
695 buf[6] = hex[(ch & 0xF0) >> 4];
696 buf[7] = hex[(ch & 0xF)];
697 scm_lfwrite (buf, 8, port);
698 j = i + 1;
699 }
700 }
701 }
702 scm_putc ('"', port);
703 scm_remember_upto_here_1 (exp);
704 }
705 else
706 scm_lfwrite_str (exp, port);
707 scm_remember_upto_here_1 (exp);
708 break;
709 case scm_tc7_symbol:
710 if (scm_i_symbol_is_interned (exp))
711 {
712 scm_i_print_symbol_name (exp, port);
713 scm_remember_upto_here_1 (exp);
714 }
715 else
716 {
717 scm_puts ("#<uninterned-symbol ", port);
718 scm_i_print_symbol_name (exp, port);
719 scm_putc (' ', port);
720 scm_uintprint (SCM_UNPACK (exp), 16, port);
721 scm_putc ('>', port);
722 }
723 break;
724 case scm_tc7_variable:
725 scm_i_variable_print (exp, port, pstate);
726 break;
727 case scm_tc7_program:
728 scm_i_program_print (exp, port, pstate);
729 break;
730 case scm_tc7_wvect:
731 ENTER_NESTED_DATA (pstate, exp, circref);
732 if (SCM_IS_WHVEC (exp))
733 scm_puts ("#wh(", port);
734 else
735 scm_puts ("#w(", port);
736 goto common_vector_printer;
737
738 case scm_tc7_vector:
739 ENTER_NESTED_DATA (pstate, exp, circref);
740 scm_puts ("#(", port);
741 common_vector_printer:
742 {
743 register long i;
744 long last = SCM_SIMPLE_VECTOR_LENGTH (exp) - 1;
745 int cutp = 0;
746 if (pstate->fancyp
747 && SCM_SIMPLE_VECTOR_LENGTH (exp) > pstate->length)
748 {
749 last = pstate->length - 1;
750 cutp = 1;
751 }
752 for (i = 0; i < last; ++i)
753 {
754 /* CHECK_INTS; */
755 scm_iprin1 (SCM_SIMPLE_VECTOR_REF (exp, i), port, pstate);
756 scm_putc (' ', port);
757 }
758 if (i == last)
759 {
760 /* CHECK_INTS; */
761 scm_iprin1 (SCM_SIMPLE_VECTOR_REF (exp, i), port, pstate);
762 }
763 if (cutp)
764 scm_puts (" ...", port);
765 scm_putc (')', port);
766 }
767 EXIT_NESTED_DATA (pstate);
768 break;
769 case scm_tcs_subrs:
770 {
771 SCM name = scm_symbol_to_string (SCM_SUBR_NAME (exp));
772 scm_puts (SCM_SUBR_GENERIC (exp)
773 ? "#<primitive-generic "
774 : "#<primitive-procedure ",
775 port);
776 scm_lfwrite_str (name, port);
777 scm_putc ('>', port);
778 break;
779 }
780 case scm_tc7_pws:
781 scm_puts ("#<procedure-with-setter", port);
782 {
783 SCM name = scm_procedure_name (exp);
784 if (scm_is_true (name))
785 {
786 scm_putc (' ', port);
787 scm_display (name, port);
788 }
789 }
790 scm_putc ('>', port);
791 break;
792 case scm_tc7_port:
793 {
794 register long i = SCM_PTOBNUM (exp);
795 if (i < scm_numptob
796 && scm_ptobs[i].print
797 && (scm_ptobs[i].print) (exp, port, pstate))
798 break;
799 goto punk;
800 }
801 case scm_tc7_smob:
802 ENTER_NESTED_DATA (pstate, exp, circref);
803 SCM_SMOB_DESCRIPTOR (exp).print (exp, port, pstate);
804 EXIT_NESTED_DATA (pstate);
805 break;
806 default:
807 punk:
808 scm_ipruk ("type", exp, port);
809 }
810 }
811 }
812
813 /* Print states are necessary for circular reference safe printing.
814 * They are also expensive to allocate. Therefore print states are
815 * kept in a pool so that they can be reused.
816 */
817
818 /* The PORT argument can also be a print-state/port pair, which will
819 * then be used instead of allocating a new print state. This is
820 * useful for continuing a chain of print calls from Scheme. */
821
822 void
823 scm_prin1 (SCM exp, SCM port, int writingp)
824 {
825 SCM handle = SCM_BOOL_F; /* Will GC protect the handle whilst unlinked */
826 SCM pstate_scm;
827 scm_print_state *pstate;
828 int old_writingp;
829
830 /* If PORT is a print-state/port pair, use that. Else create a new
831 print-state. */
832
833 if (SCM_PORT_WITH_PS_P (port))
834 {
835 pstate_scm = SCM_PORT_WITH_PS_PS (port);
836 port = SCM_PORT_WITH_PS_PORT (port);
837 }
838 else
839 {
840 /* First try to allocate a print state from the pool */
841 scm_i_pthread_mutex_lock (&print_state_mutex);
842 if (!scm_is_null (print_state_pool))
843 {
844 handle = print_state_pool;
845 print_state_pool = SCM_CDR (print_state_pool);
846 }
847 scm_i_pthread_mutex_unlock (&print_state_mutex);
848 if (scm_is_false (handle))
849 handle = scm_list_1 (make_print_state ());
850 pstate_scm = SCM_CAR (handle);
851 }
852
853 pstate = SCM_PRINT_STATE (pstate_scm);
854 old_writingp = pstate->writingp;
855 pstate->writingp = writingp;
856 scm_iprin1 (exp, port, pstate);
857 pstate->writingp = old_writingp;
858
859 /* Return print state to pool if it has been created above and
860 hasn't escaped to Scheme. */
861
862 if (scm_is_true (handle) && !pstate->revealed)
863 {
864 scm_i_pthread_mutex_lock (&print_state_mutex);
865 SCM_SETCDR (handle, print_state_pool);
866 print_state_pool = handle;
867 scm_i_pthread_mutex_unlock (&print_state_mutex);
868 }
869 }
870
871 /* Print a character.
872 */
873 void
874 scm_i_charprint (scm_t_wchar ch, SCM port)
875 {
876 scm_t_wchar *wbuf;
877 SCM wstr = scm_i_make_wide_string (1, &wbuf);
878
879 wbuf[0] = ch;
880 scm_lfwrite_str (wstr, port);
881 }
882
883 /* Print an integer.
884 */
885
886 void
887 scm_intprint (scm_t_intmax n, int radix, SCM port)
888 {
889 char num_buf[SCM_INTBUFLEN];
890 scm_lfwrite (num_buf, scm_iint2str (n, radix, num_buf), port);
891 }
892
893 void
894 scm_uintprint (scm_t_uintmax n, int radix, SCM port)
895 {
896 char num_buf[SCM_INTBUFLEN];
897 scm_lfwrite (num_buf, scm_iuint2str (n, radix, num_buf), port);
898 }
899
900 /* Print an object of unrecognized type.
901 */
902
903 void
904 scm_ipruk (char *hdr, SCM ptr, SCM port)
905 {
906 scm_puts ("#<unknown-", port);
907 scm_puts (hdr, port);
908 if (scm_in_heap_p (ptr))
909 {
910 scm_puts (" (0x", port);
911 scm_uintprint (SCM_CELL_WORD_0 (ptr), 16, port);
912 scm_puts (" . 0x", port);
913 scm_uintprint (SCM_CELL_WORD_1 (ptr), 16, port);
914 scm_puts (") @", port);
915 }
916 scm_puts (" 0x", port);
917 scm_uintprint (SCM_UNPACK (ptr), 16, port);
918 scm_putc ('>', port);
919 }
920
921
922 /* Print a list.
923 */
924 void
925 scm_iprlist (char *hdr, SCM exp, int tlr, SCM port, scm_print_state *pstate)
926 {
927 register SCM hare, tortoise;
928 long floor = pstate->top - 2;
929 scm_puts (hdr, port);
930 /* CHECK_INTS; */
931 if (pstate->fancyp)
932 goto fancy_printing;
933
934 /* Run a hare and tortoise so that total time complexity will be
935 O(depth * N) instead of O(N^2). */
936 hare = SCM_CDR (exp);
937 tortoise = exp;
938 while (scm_is_pair (hare))
939 {
940 if (scm_is_eq (hare, tortoise))
941 goto fancy_printing;
942 hare = SCM_CDR (hare);
943 if (!scm_is_pair (hare))
944 break;
945 hare = SCM_CDR (hare);
946 tortoise = SCM_CDR (tortoise);
947 }
948
949 /* No cdr cycles intrinsic to this list */
950 scm_iprin1 (SCM_CAR (exp), port, pstate);
951 for (exp = SCM_CDR (exp); scm_is_pair (exp); exp = SCM_CDR (exp))
952 {
953 register long i;
954
955 for (i = floor; i >= 0; --i)
956 if (scm_is_eq (PSTATE_STACK_REF(pstate, i), exp))
957 goto circref;
958 PUSH_REF (pstate, exp);
959 scm_putc (' ', port);
960 /* CHECK_INTS; */
961 scm_iprin1 (SCM_CAR (exp), port, pstate);
962 }
963 if (!SCM_NULL_OR_NIL_P (exp))
964 {
965 scm_puts (" . ", port);
966 scm_iprin1 (exp, port, pstate);
967 }
968
969 end:
970 scm_putc (tlr, port);
971 pstate->top = floor + 2;
972 return;
973
974 fancy_printing:
975 {
976 long n = pstate->length;
977
978 scm_iprin1 (SCM_CAR (exp), port, pstate);
979 exp = SCM_CDR (exp); --n;
980 for (; scm_is_pair (exp); exp = SCM_CDR (exp))
981 {
982 register unsigned long i;
983
984 for (i = 0; i < pstate->top; ++i)
985 if (scm_is_eq (PSTATE_STACK_REF(pstate, i), exp))
986 goto fancy_circref;
987 if (pstate->fancyp)
988 {
989 if (n == 0)
990 {
991 scm_puts (" ...", port);
992 goto skip_tail;
993 }
994 else
995 --n;
996 }
997 PUSH_REF(pstate, exp);
998 ++pstate->list_offset;
999 scm_putc (' ', port);
1000 /* CHECK_INTS; */
1001 scm_iprin1 (SCM_CAR (exp), port, pstate);
1002 }
1003 }
1004 if (!SCM_NULL_OR_NIL_P (exp))
1005 {
1006 scm_puts (" . ", port);
1007 scm_iprin1 (exp, port, pstate);
1008 }
1009 skip_tail:
1010 pstate->list_offset -= pstate->top - floor - 2;
1011 goto end;
1012
1013 fancy_circref:
1014 pstate->list_offset -= pstate->top - floor - 2;
1015
1016 circref:
1017 scm_puts (" . ", port);
1018 print_circref (port, pstate, exp);
1019 goto end;
1020 }
1021
1022 \f
1023
1024 int
1025 scm_valid_oport_value_p (SCM val)
1026 {
1027 return (SCM_OPOUTPORTP (val)
1028 || (SCM_PORT_WITH_PS_P (val)
1029 && SCM_OPOUTPORTP (SCM_PORT_WITH_PS_PORT (val))));
1030 }
1031
1032 /* SCM_GPROC(s_write, "write", 1, 1, 0, scm_write, g_write); */
1033
1034 SCM
1035 scm_write (SCM obj, SCM port)
1036 {
1037 if (SCM_UNBNDP (port))
1038 port = scm_current_output_port ();
1039
1040 SCM_ASSERT (scm_valid_oport_value_p (port), port, SCM_ARG2, s_write);
1041
1042 scm_prin1 (obj, port, 1);
1043 #if 0
1044 #ifdef HAVE_PIPE
1045 # ifdef EPIPE
1046 if (EPIPE == errno)
1047 scm_close_port (port);
1048 # endif
1049 #endif
1050 #endif
1051 return SCM_UNSPECIFIED;
1052 }
1053
1054
1055 /* SCM_GPROC(s_display, "display", 1, 1, 0, scm_display, g_display); */
1056
1057 SCM
1058 scm_display (SCM obj, SCM port)
1059 {
1060 if (SCM_UNBNDP (port))
1061 port = scm_current_output_port ();
1062
1063 SCM_ASSERT (scm_valid_oport_value_p (port), port, SCM_ARG2, s_display);
1064
1065 scm_prin1 (obj, port, 0);
1066 #if 0
1067 #ifdef HAVE_PIPE
1068 # ifdef EPIPE
1069 if (EPIPE == errno)
1070 scm_close_port (port);
1071 # endif
1072 #endif
1073 #endif
1074 return SCM_UNSPECIFIED;
1075 }
1076
1077
1078 SCM_DEFINE (scm_simple_format, "simple-format", 2, 0, 1,
1079 (SCM destination, SCM message, SCM args),
1080 "Write @var{message} to @var{destination}, defaulting to\n"
1081 "the current output port.\n"
1082 "@var{message} can contain @code{~A} (was @code{%s}) and\n"
1083 "@code{~S} (was @code{%S}) escapes. When printed,\n"
1084 "the escapes are replaced with corresponding members of\n"
1085 "@var{ARGS}:\n"
1086 "@code{~A} formats using @code{display} and @code{~S} formats\n"
1087 "using @code{write}.\n"
1088 "If @var{destination} is @code{#t}, then use the current output\n"
1089 "port, if @var{destination} is @code{#f}, then return a string\n"
1090 "containing the formatted text. Does not add a trailing newline.")
1091 #define FUNC_NAME s_scm_simple_format
1092 {
1093 SCM port, answer = SCM_UNSPECIFIED;
1094 int fReturnString = 0;
1095 int writingp;
1096 size_t start, p, end;
1097
1098 if (scm_is_eq (destination, SCM_BOOL_T))
1099 {
1100 destination = port = scm_current_output_port ();
1101 }
1102 else if (scm_is_false (destination))
1103 {
1104 fReturnString = 1;
1105 port = scm_mkstrport (SCM_INUM0,
1106 scm_make_string (SCM_INUM0, SCM_UNDEFINED),
1107 SCM_OPN | SCM_WRTNG,
1108 FUNC_NAME);
1109 destination = port;
1110 }
1111 else
1112 {
1113 SCM_VALIDATE_OPORT_VALUE (1, destination);
1114 port = SCM_COERCE_OUTPORT (destination);
1115 }
1116 SCM_VALIDATE_STRING (2, message);
1117 SCM_VALIDATE_REST_ARGUMENT (args);
1118
1119 p = 0;
1120 start = 0;
1121 end = scm_i_string_length (message);
1122 for (p = start; p != end; ++p)
1123 if (scm_i_string_ref (message, p) == '~')
1124 {
1125 if (++p == end)
1126 break;
1127
1128 switch (scm_i_string_ref (message, p))
1129 {
1130 case 'A': case 'a':
1131 writingp = 0;
1132 break;
1133 case 'S': case 's':
1134 writingp = 1;
1135 break;
1136 case '~':
1137 scm_lfwrite_substr (message, start, p, port);
1138 start = p + 1;
1139 continue;
1140 case '%':
1141 scm_lfwrite_substr (message, start, p - 1, port);
1142 scm_newline (port);
1143 start = p + 1;
1144 continue;
1145 default:
1146 SCM_MISC_ERROR ("FORMAT: Unsupported format option ~~~A - use (ice-9 format) instead",
1147 scm_list_1 (SCM_MAKE_CHAR (scm_i_string_ref (message, p))));
1148
1149 }
1150
1151
1152 if (!scm_is_pair (args))
1153 SCM_MISC_ERROR ("FORMAT: Missing argument for ~~~A",
1154 scm_list_1 (SCM_MAKE_CHAR (scm_i_string_ref (message, p))));
1155
1156 scm_lfwrite_substr (message, start, p - 1, port);
1157 /* we pass destination here */
1158 scm_prin1 (SCM_CAR (args), destination, writingp);
1159 args = SCM_CDR (args);
1160 start = p + 1;
1161 }
1162
1163 scm_lfwrite_substr (message, start, p, port);
1164 if (!scm_is_eq (args, SCM_EOL))
1165 SCM_MISC_ERROR ("FORMAT: ~A superfluous arguments",
1166 scm_list_1 (scm_length (args)));
1167
1168 if (fReturnString)
1169 answer = scm_strport_to_string (destination);
1170
1171 return scm_return_first (answer, message);
1172 }
1173 #undef FUNC_NAME
1174
1175
1176 SCM_DEFINE (scm_newline, "newline", 0, 1, 0,
1177 (SCM port),
1178 "Send a newline to @var{port}.\n"
1179 "If @var{port} is omitted, send to the current output port.")
1180 #define FUNC_NAME s_scm_newline
1181 {
1182 if (SCM_UNBNDP (port))
1183 port = scm_current_output_port ();
1184
1185 SCM_VALIDATE_OPORT_VALUE (1, port);
1186
1187 scm_putc ('\n', SCM_COERCE_OUTPORT (port));
1188 return SCM_UNSPECIFIED;
1189 }
1190 #undef FUNC_NAME
1191
1192 SCM_DEFINE (scm_write_char, "write-char", 1, 1, 0,
1193 (SCM chr, SCM port),
1194 "Send character @var{chr} to @var{port}.")
1195 #define FUNC_NAME s_scm_write_char
1196 {
1197 if (SCM_UNBNDP (port))
1198 port = scm_current_output_port ();
1199
1200 SCM_VALIDATE_CHAR (1, chr);
1201 SCM_VALIDATE_OPORT_VALUE (2, port);
1202
1203 scm_putc ((int) SCM_CHAR (chr), SCM_COERCE_OUTPORT (port));
1204 #if 0
1205 #ifdef HAVE_PIPE
1206 # ifdef EPIPE
1207 if (EPIPE == errno)
1208 scm_close_port (port);
1209 # endif
1210 #endif
1211 #endif
1212 return SCM_UNSPECIFIED;
1213 }
1214 #undef FUNC_NAME
1215
1216 \f
1217
1218 /* Call back to Scheme code to do the printing of special objects
1219 * (like structs). SCM_PRINTER_APPLY applies PROC to EXP and a smob
1220 * containing PORT and PSTATE. This object can be used as the port for
1221 * display/write etc to continue the current print chain. The REVEALED
1222 * field of PSTATE is set to true to indicate that the print state has
1223 * escaped to Scheme and thus has to be freed by the GC.
1224 */
1225
1226 scm_t_bits scm_tc16_port_with_ps;
1227
1228 /* Print exactly as the port itself would */
1229
1230 static int
1231 port_with_ps_print (SCM obj, SCM port, scm_print_state *pstate)
1232 {
1233 obj = SCM_PORT_WITH_PS_PORT (obj);
1234 return scm_ptobs[SCM_PTOBNUM (obj)].print (obj, port, pstate);
1235 }
1236
1237 SCM
1238 scm_printer_apply (SCM proc, SCM exp, SCM port, scm_print_state *pstate)
1239 {
1240 pstate->revealed = 1;
1241 return scm_call_2 (proc, exp,
1242 scm_i_port_with_print_state (port, pstate->handle));
1243 }
1244
1245 SCM_DEFINE (scm_port_with_print_state, "port-with-print-state", 1, 1, 0,
1246 (SCM port, SCM pstate),
1247 "Create a new port which behaves like @var{port}, but with an\n"
1248 "included print state @var{pstate}. @var{pstate} is optional.\n"
1249 "If @var{pstate} isn't supplied and @var{port} already has\n"
1250 "a print state, the old print state is reused.")
1251 #define FUNC_NAME s_scm_port_with_print_state
1252 {
1253 SCM_VALIDATE_OPORT_VALUE (1, port);
1254 if (!SCM_UNBNDP (pstate))
1255 SCM_VALIDATE_PRINTSTATE (2, pstate);
1256 return scm_i_port_with_print_state (port, pstate);
1257 }
1258 #undef FUNC_NAME
1259
1260 SCM_DEFINE (scm_get_print_state, "get-print-state", 1, 0, 0,
1261 (SCM port),
1262 "Return the print state of the port @var{port}. If @var{port}\n"
1263 "has no associated print state, @code{#f} is returned.")
1264 #define FUNC_NAME s_scm_get_print_state
1265 {
1266 if (SCM_PORT_WITH_PS_P (port))
1267 return SCM_PORT_WITH_PS_PS (port);
1268 if (SCM_OUTPUT_PORT_P (port))
1269 return SCM_BOOL_F;
1270 SCM_WRONG_TYPE_ARG (1, port);
1271 }
1272 #undef FUNC_NAME
1273
1274 \f
1275
1276 void
1277 scm_init_print ()
1278 {
1279 SCM vtable, layout, type;
1280
1281 scm_init_opts (scm_print_options, scm_print_opts);
1282
1283 scm_print_options (scm_list_4 (scm_from_locale_symbol ("highlight-prefix"),
1284 scm_from_locale_string ("{"),
1285 scm_from_locale_symbol ("highlight-suffix"),
1286 scm_from_locale_string ("}")));
1287
1288 scm_gc_register_root (&print_state_pool);
1289 scm_gc_register_root (&scm_print_state_vtable);
1290 vtable = scm_make_vtable_vtable (scm_nullstr, SCM_INUM0, SCM_EOL);
1291 layout =
1292 scm_make_struct_layout (scm_from_locale_string (SCM_PRINT_STATE_LAYOUT));
1293 type = scm_make_struct (vtable, SCM_INUM0, scm_list_1 (layout));
1294 scm_set_struct_vtable_name_x (type, scm_from_locale_symbol ("print-state"));
1295 scm_print_state_vtable = type;
1296
1297 /* Don't want to bind a wrapper class in GOOPS, so pass 0 as arg1. */
1298 scm_tc16_port_with_ps = scm_make_smob_type (0, 0);
1299 scm_set_smob_mark (scm_tc16_port_with_ps, scm_markcdr);
1300 scm_set_smob_print (scm_tc16_port_with_ps, port_with_ps_print);
1301
1302 #include "libguile/print.x"
1303
1304 scm_print_opts[SCM_PRINT_KEYWORD_STYLE_I].val = SCM_UNPACK (sym_reader);
1305 }
1306
1307 /*
1308 Local Variables:
1309 c-file-style: "gnu"
1310 End:
1311 */