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