Merge branch 'master' into boehm-demers-weiser-gc
[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/alist.h"
40 #include "libguile/struct.h"
41 #include "libguile/objects.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/lang.h"
48 #include "libguile/numbers.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 "#t",
67 "#<undefined>",
68 "#<eof>",
69 "()",
70 "#<unspecified>",
71
72 /* Unbound slot marker for GOOPS. For internal use in GOOPS only. */
73 "#<unbound>",
74
75 /* Elisp nil value. This is its Scheme name; whenever it's printed in
76 * Elisp, it should appear as the symbol `nil'. */
77 "#nil"
78 };
79
80 SCM_SYMBOL (sym_reader, "reader");
81
82 scm_t_option scm_print_opts[] = {
83 { SCM_OPTION_SCM, "closure-hook", SCM_UNPACK (SCM_BOOL_F),
84 "Hook for printing closures (should handle macros as well)." },
85 { SCM_OPTION_BOOLEAN, "source", 0,
86 "Print closures with source." },
87 { SCM_OPTION_SCM, "highlight-prefix", (unsigned long)SCM_BOOL_F,
88 "The string to print before highlighted values." },
89 { SCM_OPTION_SCM, "highlight-suffix", (unsigned long)SCM_BOOL_F,
90 "The string to print after highlighted values." },
91 { SCM_OPTION_SCM, "quote-keywordish-symbols", (unsigned long)SCM_BOOL_F,
92 "How to print symbols that have a colon as their first or last character. "
93 "The value '#f' does not quote the colons; '#t' quotes them; "
94 "'reader' quotes them when the reader option 'keywords' is not '#f'."
95 },
96 { 0 },
97
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 return 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 void
415 scm_iprin1 (SCM exp, SCM port, scm_print_state *pstate)
416 {
417 if (pstate->fancyp
418 && scm_is_true (scm_memq (exp, pstate->highlight_objects)))
419 {
420 scm_display (SCM_PRINT_HIGHLIGHT_PREFIX, port);
421 iprin1 (exp, port, pstate);
422 scm_display (SCM_PRINT_HIGHLIGHT_SUFFIX, port);
423 }
424 else
425 iprin1 (exp, port, pstate);
426 }
427
428 static void
429 iprin1 (SCM exp, SCM port, scm_print_state *pstate)
430 {
431 switch (SCM_ITAG3 (exp))
432 {
433 case scm_tc3_closure:
434 case scm_tc3_tc7_1:
435 case scm_tc3_tc7_2:
436 /* These tc3 tags should never occur in an immediate value. They are
437 * only used in cell types of non-immediates, i. e. the value returned
438 * by SCM_CELL_TYPE (exp) can use these tags.
439 */
440 scm_ipruk ("immediate", exp, port);
441 break;
442 case scm_tc3_int_1:
443 case scm_tc3_int_2:
444 scm_intprint (SCM_I_INUM (exp), 10, port);
445 break;
446 case scm_tc3_imm24:
447 if (SCM_CHARP (exp))
448 {
449 scm_t_wchar i = SCM_CHAR (exp);
450 const char *name;
451
452 if (SCM_WRITINGP (pstate))
453 {
454 scm_puts ("#\\", port);
455 name = scm_i_charname (exp);
456 if (name != NULL)
457 scm_puts (name, port);
458 else if (uc_is_general_category_withtable (i, UC_CATEGORY_MASK_L
459 | UC_CATEGORY_MASK_M
460 | UC_CATEGORY_MASK_N
461 | UC_CATEGORY_MASK_P
462 | UC_CATEGORY_MASK_S))
463 /* Print the character if is graphic character. */
464 {
465 scm_t_wchar *wbuf;
466 SCM wstr = scm_i_make_wide_string (1, &wbuf);
467 char *buf;
468 size_t len;
469 const char *enc;
470
471 enc = scm_i_get_port_encoding (port);
472 wbuf[0] = i;
473 if (enc == NULL)
474 {
475 if (i <= 0xFF)
476 /* Character is graphic and Latin-1. Print it */
477 scm_lfwrite_str (wstr, port);
478 else
479 /* Character is graphic but unrepresentable in
480 this port's encoding. */
481 scm_intprint (i, 8, port);
482 }
483 else
484 {
485 buf = u32_conv_to_encoding (enc,
486 iconveh_error,
487 (scm_t_uint32 *) wbuf,
488 1,
489 NULL,
490 NULL, &len);
491 if (buf != NULL)
492 {
493 /* Character is graphic. Print it. */
494 scm_lfwrite_str (wstr, port);
495 free (buf);
496 }
497 else
498 /* Character is graphic but unrepresentable in
499 this port's encoding. */
500 scm_intprint (i, 8, port);
501 }
502 }
503 else
504 /* Character is a non-graphical character. */
505 scm_intprint (i, 8, port);
506 }
507 else
508 scm_i_charprint (i, port);
509 }
510 else if (SCM_IFLAGP (exp)
511 && ((size_t) SCM_IFLAGNUM (exp) < (sizeof iflagnames / sizeof (char *))))
512 {
513 scm_puts (iflagnames [SCM_IFLAGNUM (exp)], port);
514 }
515 else if (SCM_ISYMP (exp))
516 {
517 scm_i_print_isym (exp, port);
518 }
519 else if (SCM_ILOCP (exp))
520 {
521 scm_i_print_iloc (exp, port);
522 }
523 else
524 {
525 /* unknown immediate value */
526 scm_ipruk ("immediate", exp, port);
527 }
528 break;
529 case scm_tc3_cons:
530 switch (SCM_TYP7 (exp))
531 {
532 case scm_tcs_struct:
533 {
534 ENTER_NESTED_DATA (pstate, exp, circref);
535 if (SCM_OBJ_CLASS_FLAGS (exp) & SCM_CLASSF_GOOPS)
536 {
537 SCM pwps, print = pstate->writingp ? g_write : g_display;
538 if (!print)
539 goto print_struct;
540 pwps = scm_i_port_with_print_state (port, pstate->handle);
541 pstate->revealed = 1;
542 scm_call_generic_2 (print, exp, pwps);
543 }
544 else
545 {
546 print_struct:
547 scm_print_struct (exp, port, pstate);
548 }
549 EXIT_NESTED_DATA (pstate);
550 }
551 break;
552 case scm_tcs_cons_imcar:
553 case scm_tcs_cons_nimcar:
554 ENTER_NESTED_DATA (pstate, exp, circref);
555 scm_iprlist ("(", exp, ')', port, pstate);
556 EXIT_NESTED_DATA (pstate);
557 break;
558 circref:
559 print_circref (port, pstate, exp);
560 break;
561 case scm_tcs_closures:
562 if (scm_is_false (scm_procedure_p (SCM_PRINT_CLOSURE))
563 || scm_is_false (scm_printer_apply (SCM_PRINT_CLOSURE,
564 exp, port, pstate)))
565 {
566 SCM formals = SCM_CLOSURE_FORMALS (exp);
567 scm_puts ("#<procedure", port);
568 scm_putc (' ', port);
569 scm_iprin1 (scm_procedure_name (exp), port, pstate);
570 scm_putc (' ', port);
571 if (SCM_PRINT_SOURCE_P)
572 {
573 SCM env = SCM_ENV (exp);
574 SCM xenv = SCM_EXTEND_ENV (formals, SCM_EOL, env);
575 SCM src = scm_i_unmemocopy_body (SCM_CODE (exp), xenv);
576 ENTER_NESTED_DATA (pstate, exp, circref);
577 scm_iprin1 (src, port, pstate);
578 EXIT_NESTED_DATA (pstate);
579 }
580 else
581 scm_iprin1 (formals, port, pstate);
582 scm_putc ('>', port);
583 }
584 break;
585 case scm_tc7_number:
586 switch SCM_TYP16 (exp) {
587 case scm_tc16_big:
588 scm_bigprint (exp, port, pstate);
589 break;
590 case scm_tc16_real:
591 scm_print_real (exp, port, pstate);
592 break;
593 case scm_tc16_complex:
594 scm_print_complex (exp, port, pstate);
595 break;
596 case scm_tc16_fraction:
597 scm_i_print_fraction (exp, port, pstate);
598 break;
599 }
600 break;
601 case scm_tc7_string:
602 if (SCM_WRITINGP (pstate))
603 {
604 size_t i, j, len;
605 static char const hex[] = "0123456789abcdef";
606 char buf[8];
607
608
609 scm_putc ('"', port);
610 len = scm_i_string_length (exp);
611 for (i = 0; i < len; ++i)
612 {
613 scm_t_wchar ch = scm_i_string_ref (exp, i);
614 int printed = 0;
615
616 if (ch == ' ' || ch == '\n')
617 {
618 scm_putc (ch, port);
619 printed = 1;
620 }
621 else if (ch == '"' || ch == '\\')
622 {
623 scm_putc ('\\', port);
624 scm_i_charprint (ch, port);
625 printed = 1;
626 }
627 else
628 if (uc_is_general_category_withtable
629 (ch,
630 UC_CATEGORY_MASK_L | UC_CATEGORY_MASK_M |
631 UC_CATEGORY_MASK_N | UC_CATEGORY_MASK_P |
632 UC_CATEGORY_MASK_S))
633 {
634 /* Print the character since it is a graphic
635 character. */
636 scm_t_wchar *wbuf;
637 SCM wstr = scm_i_make_wide_string (1, &wbuf);
638 char *buf;
639 size_t len;
640
641 if (scm_i_get_port_encoding (port))
642 {
643 wstr = scm_i_make_wide_string (1, &wbuf);
644 wbuf[0] = ch;
645 buf = u32_conv_to_encoding (scm_i_get_port_encoding (port),
646 iconveh_error,
647 (scm_t_uint32 *) wbuf,
648 1 ,
649 NULL,
650 NULL, &len);
651 if (buf != NULL)
652 {
653 /* Character is graphic and representable in
654 this encoding. Print it. */
655 scm_lfwrite_str (wstr, port);
656 free (buf);
657 printed = 1;
658 }
659 }
660 else
661 if (ch <= 0xFF)
662 {
663 scm_putc (ch, port);
664 printed = 1;
665 }
666 }
667
668 if (!printed)
669 {
670 /* Character is graphic but unrepresentable in
671 this port's encoding or is not graphic. */
672 if (ch <= 0xFF)
673 {
674 buf[0] = '\\';
675 buf[1] = 'x';
676 buf[2] = hex[ch / 16];
677 buf[3] = hex[ch % 16];
678 scm_lfwrite (buf, 4, port);
679 }
680 else if (ch <= 0xFFFF)
681 {
682 buf[0] = '\\';
683 buf[1] = 'u';
684 buf[2] = hex[(ch & 0xF000) >> 12];
685 buf[3] = hex[(ch & 0xF00) >> 8];
686 buf[4] = hex[(ch & 0xF0) >> 4];
687 buf[5] = hex[(ch & 0xF)];
688 scm_lfwrite (buf, 6, port);
689 j = i + 1;
690 }
691 else if (ch > 0xFFFF)
692 {
693 buf[0] = '\\';
694 buf[1] = 'U';
695 buf[2] = hex[(ch & 0xF00000) >> 20];
696 buf[3] = hex[(ch & 0xF0000) >> 16];
697 buf[4] = hex[(ch & 0xF000) >> 12];
698 buf[5] = hex[(ch & 0xF00) >> 8];
699 buf[6] = hex[(ch & 0xF0) >> 4];
700 buf[7] = hex[(ch & 0xF)];
701 scm_lfwrite (buf, 8, port);
702 j = i + 1;
703 }
704 }
705 }
706 scm_putc ('"', port);
707 scm_remember_upto_here_1 (exp);
708 }
709 else
710 scm_lfwrite_str (exp, port);
711 scm_remember_upto_here_1 (exp);
712 break;
713 case scm_tc7_symbol:
714 if (scm_i_symbol_is_interned (exp))
715 {
716 scm_i_print_symbol_name (exp, port);
717 scm_remember_upto_here_1 (exp);
718 }
719 else
720 {
721 scm_puts ("#<uninterned-symbol ", port);
722 scm_i_print_symbol_name (exp, port);
723 scm_putc (' ', port);
724 scm_uintprint (SCM_UNPACK (exp), 16, port);
725 scm_putc ('>', port);
726 }
727 break;
728 case scm_tc7_variable:
729 scm_i_variable_print (exp, port, pstate);
730 break;
731 case scm_tc7_program:
732 scm_i_program_print (exp, port, pstate);
733 break;
734 case scm_tc7_wvect:
735 ENTER_NESTED_DATA (pstate, exp, circref);
736 if (SCM_IS_WHVEC (exp))
737 scm_puts ("#wh(", port);
738 else
739 scm_puts ("#w(", port);
740 goto common_vector_printer;
741
742 case scm_tc7_vector:
743 ENTER_NESTED_DATA (pstate, exp, circref);
744 scm_puts ("#(", port);
745 common_vector_printer:
746 {
747 register long i;
748 long last = SCM_SIMPLE_VECTOR_LENGTH (exp) - 1;
749 int cutp = 0;
750 if (pstate->fancyp
751 && SCM_SIMPLE_VECTOR_LENGTH (exp) > pstate->length)
752 {
753 last = pstate->length - 1;
754 cutp = 1;
755 }
756 if (SCM_I_WVECTP (exp))
757 {
758 /* Elements of weak vectors may not be accessed via the
759 `SIMPLE_VECTOR_REF ()' macro. */
760 for (i = 0; i < last; ++i)
761 {
762 scm_iprin1 (scm_c_vector_ref (exp, i),
763 port, pstate);
764 scm_putc (' ', port);
765 }
766 }
767 else
768 {
769 for (i = 0; i < last; ++i)
770 {
771 scm_iprin1 (SCM_SIMPLE_VECTOR_REF (exp, i), port, pstate);
772 scm_putc (' ', port);
773 }
774 }
775
776 if (i == last)
777 {
778 /* CHECK_INTS; */
779 scm_iprin1 (scm_c_vector_ref (exp, i), port, pstate);
780 }
781 if (cutp)
782 scm_puts (" ...", port);
783 scm_putc (')', port);
784 }
785 EXIT_NESTED_DATA (pstate);
786 break;
787 case scm_tcs_subrs:
788 {
789 SCM name = scm_symbol_to_string (SCM_SUBR_NAME (exp));
790 scm_puts (SCM_SUBR_GENERIC (exp)
791 ? "#<primitive-generic "
792 : "#<primitive-procedure ",
793 port);
794 scm_lfwrite_str (name, port);
795 scm_putc ('>', port);
796 break;
797 }
798 case scm_tc7_pws:
799 scm_puts ("#<procedure-with-setter", port);
800 {
801 SCM name = scm_procedure_name (exp);
802 if (scm_is_true (name))
803 {
804 scm_putc (' ', port);
805 scm_display (name, port);
806 }
807 }
808 scm_putc ('>', port);
809 break;
810 case scm_tc7_port:
811 {
812 register long i = SCM_PTOBNUM (exp);
813 if (i < scm_numptob
814 && scm_ptobs[i].print
815 && (scm_ptobs[i].print) (exp, port, pstate))
816 break;
817 goto punk;
818 }
819 case scm_tc7_smob:
820 ENTER_NESTED_DATA (pstate, exp, circref);
821 SCM_SMOB_DESCRIPTOR (exp).print (exp, port, pstate);
822 EXIT_NESTED_DATA (pstate);
823 break;
824 default:
825 punk:
826 scm_ipruk ("type", exp, port);
827 }
828 }
829 }
830
831 /* Print states are necessary for circular reference safe printing.
832 * They are also expensive to allocate. Therefore print states are
833 * kept in a pool so that they can be reused.
834 */
835
836 /* The PORT argument can also be a print-state/port pair, which will
837 * then be used instead of allocating a new print state. This is
838 * useful for continuing a chain of print calls from Scheme. */
839
840 void
841 scm_prin1 (SCM exp, SCM port, int writingp)
842 {
843 SCM handle = SCM_BOOL_F; /* Will GC protect the handle whilst unlinked */
844 SCM pstate_scm;
845 scm_print_state *pstate;
846 int old_writingp;
847
848 /* If PORT is a print-state/port pair, use that. Else create a new
849 print-state. */
850
851 if (SCM_PORT_WITH_PS_P (port))
852 {
853 pstate_scm = SCM_PORT_WITH_PS_PS (port);
854 port = SCM_PORT_WITH_PS_PORT (port);
855 }
856 else
857 {
858 /* First try to allocate a print state from the pool */
859 scm_i_pthread_mutex_lock (&print_state_mutex);
860 if (!scm_is_null (print_state_pool))
861 {
862 handle = print_state_pool;
863 print_state_pool = SCM_CDR (print_state_pool);
864 }
865 scm_i_pthread_mutex_unlock (&print_state_mutex);
866 if (scm_is_false (handle))
867 handle = scm_list_1 (make_print_state ());
868 pstate_scm = SCM_CAR (handle);
869 }
870
871 pstate = SCM_PRINT_STATE (pstate_scm);
872 old_writingp = pstate->writingp;
873 pstate->writingp = writingp;
874 scm_iprin1 (exp, port, pstate);
875 pstate->writingp = old_writingp;
876
877 /* Return print state to pool if it has been created above and
878 hasn't escaped to Scheme. */
879
880 if (scm_is_true (handle) && !pstate->revealed)
881 {
882 scm_i_pthread_mutex_lock (&print_state_mutex);
883 SCM_SETCDR (handle, print_state_pool);
884 print_state_pool = handle;
885 scm_i_pthread_mutex_unlock (&print_state_mutex);
886 }
887 }
888
889 /* Print a character.
890 */
891 void
892 scm_i_charprint (scm_t_wchar ch, SCM port)
893 {
894 scm_t_wchar *wbuf;
895 SCM wstr = scm_i_make_wide_string (1, &wbuf);
896
897 wbuf[0] = ch;
898 scm_lfwrite_str (wstr, port);
899 }
900
901 /* Print an integer.
902 */
903
904 void
905 scm_intprint (scm_t_intmax n, int radix, SCM port)
906 {
907 char num_buf[SCM_INTBUFLEN];
908 scm_lfwrite (num_buf, scm_iint2str (n, radix, num_buf), port);
909 }
910
911 void
912 scm_uintprint (scm_t_uintmax n, int radix, SCM port)
913 {
914 char num_buf[SCM_INTBUFLEN];
915 scm_lfwrite (num_buf, scm_iuint2str (n, radix, num_buf), port);
916 }
917
918 /* Print an object of unrecognized type.
919 */
920
921 void
922 scm_ipruk (char *hdr, SCM ptr, SCM port)
923 {
924 scm_puts ("#<unknown-", port);
925 scm_puts (hdr, port);
926 if (1) /* (scm_in_heap_p (ptr)) */ /* FIXME */
927 {
928 scm_puts (" (0x", port);
929 scm_uintprint (SCM_CELL_WORD_0 (ptr), 16, port);
930 scm_puts (" . 0x", port);
931 scm_uintprint (SCM_CELL_WORD_1 (ptr), 16, port);
932 scm_puts (") @", port);
933 }
934 scm_puts (" 0x", port);
935 scm_uintprint (SCM_UNPACK (ptr), 16, port);
936 scm_putc ('>', port);
937 }
938
939
940 /* Print a list.
941 */
942 void
943 scm_iprlist (char *hdr, SCM exp, int tlr, SCM port, scm_print_state *pstate)
944 {
945 register SCM hare, tortoise;
946 long floor = pstate->top - 2;
947 scm_puts (hdr, port);
948 /* CHECK_INTS; */
949 if (pstate->fancyp)
950 goto fancy_printing;
951
952 /* Run a hare and tortoise so that total time complexity will be
953 O(depth * N) instead of O(N^2). */
954 hare = SCM_CDR (exp);
955 tortoise = exp;
956 while (scm_is_pair (hare))
957 {
958 if (scm_is_eq (hare, tortoise))
959 goto fancy_printing;
960 hare = SCM_CDR (hare);
961 if (!scm_is_pair (hare))
962 break;
963 hare = SCM_CDR (hare);
964 tortoise = SCM_CDR (tortoise);
965 }
966
967 /* No cdr cycles intrinsic to this list */
968 scm_iprin1 (SCM_CAR (exp), port, pstate);
969 for (exp = SCM_CDR (exp); scm_is_pair (exp); exp = SCM_CDR (exp))
970 {
971 register long i;
972
973 for (i = floor; i >= 0; --i)
974 if (scm_is_eq (PSTATE_STACK_REF(pstate, i), exp))
975 goto circref;
976 PUSH_REF (pstate, exp);
977 scm_putc (' ', port);
978 /* CHECK_INTS; */
979 scm_iprin1 (SCM_CAR (exp), port, pstate);
980 }
981 if (!SCM_NULL_OR_NIL_P (exp))
982 {
983 scm_puts (" . ", port);
984 scm_iprin1 (exp, port, pstate);
985 }
986
987 end:
988 scm_putc (tlr, port);
989 pstate->top = floor + 2;
990 return;
991
992 fancy_printing:
993 {
994 long n = pstate->length;
995
996 scm_iprin1 (SCM_CAR (exp), port, pstate);
997 exp = SCM_CDR (exp); --n;
998 for (; scm_is_pair (exp); exp = SCM_CDR (exp))
999 {
1000 register unsigned long i;
1001
1002 for (i = 0; i < pstate->top; ++i)
1003 if (scm_is_eq (PSTATE_STACK_REF(pstate, i), exp))
1004 goto fancy_circref;
1005 if (pstate->fancyp)
1006 {
1007 if (n == 0)
1008 {
1009 scm_puts (" ...", port);
1010 goto skip_tail;
1011 }
1012 else
1013 --n;
1014 }
1015 PUSH_REF(pstate, exp);
1016 ++pstate->list_offset;
1017 scm_putc (' ', port);
1018 /* CHECK_INTS; */
1019 scm_iprin1 (SCM_CAR (exp), port, pstate);
1020 }
1021 }
1022 if (!SCM_NULL_OR_NIL_P (exp))
1023 {
1024 scm_puts (" . ", port);
1025 scm_iprin1 (exp, port, pstate);
1026 }
1027 skip_tail:
1028 pstate->list_offset -= pstate->top - floor - 2;
1029 goto end;
1030
1031 fancy_circref:
1032 pstate->list_offset -= pstate->top - floor - 2;
1033
1034 circref:
1035 scm_puts (" . ", port);
1036 print_circref (port, pstate, exp);
1037 goto end;
1038 }
1039
1040 \f
1041
1042 int
1043 scm_valid_oport_value_p (SCM val)
1044 {
1045 return (SCM_OPOUTPORTP (val)
1046 || (SCM_PORT_WITH_PS_P (val)
1047 && SCM_OPOUTPORTP (SCM_PORT_WITH_PS_PORT (val))));
1048 }
1049
1050 /* SCM_GPROC(s_write, "write", 1, 1, 0, scm_write, g_write); */
1051
1052 SCM
1053 scm_write (SCM obj, SCM port)
1054 {
1055 if (SCM_UNBNDP (port))
1056 port = scm_current_output_port ();
1057
1058 SCM_ASSERT (scm_valid_oport_value_p (port), port, SCM_ARG2, s_write);
1059
1060 scm_prin1 (obj, port, 1);
1061 #if 0
1062 #ifdef HAVE_PIPE
1063 # ifdef EPIPE
1064 if (EPIPE == errno)
1065 scm_close_port (port);
1066 # endif
1067 #endif
1068 #endif
1069 return SCM_UNSPECIFIED;
1070 }
1071
1072
1073 /* SCM_GPROC(s_display, "display", 1, 1, 0, scm_display, g_display); */
1074
1075 SCM
1076 scm_display (SCM obj, SCM port)
1077 {
1078 if (SCM_UNBNDP (port))
1079 port = scm_current_output_port ();
1080
1081 SCM_ASSERT (scm_valid_oport_value_p (port), port, SCM_ARG2, s_display);
1082
1083 scm_prin1 (obj, port, 0);
1084 #if 0
1085 #ifdef HAVE_PIPE
1086 # ifdef EPIPE
1087 if (EPIPE == errno)
1088 scm_close_port (port);
1089 # endif
1090 #endif
1091 #endif
1092 return SCM_UNSPECIFIED;
1093 }
1094
1095
1096 SCM_DEFINE (scm_simple_format, "simple-format", 2, 0, 1,
1097 (SCM destination, SCM message, SCM args),
1098 "Write @var{message} to @var{destination}, defaulting to\n"
1099 "the current output port.\n"
1100 "@var{message} can contain @code{~A} (was @code{%s}) and\n"
1101 "@code{~S} (was @code{%S}) escapes. When printed,\n"
1102 "the escapes are replaced with corresponding members of\n"
1103 "@var{ARGS}:\n"
1104 "@code{~A} formats using @code{display} and @code{~S} formats\n"
1105 "using @code{write}.\n"
1106 "If @var{destination} is @code{#t}, then use the current output\n"
1107 "port, if @var{destination} is @code{#f}, then return a string\n"
1108 "containing the formatted text. Does not add a trailing newline.")
1109 #define FUNC_NAME s_scm_simple_format
1110 {
1111 SCM port, answer = SCM_UNSPECIFIED;
1112 int fReturnString = 0;
1113 int writingp;
1114 size_t start, p, end;
1115
1116 if (scm_is_eq (destination, SCM_BOOL_T))
1117 {
1118 destination = port = scm_current_output_port ();
1119 }
1120 else if (scm_is_false (destination))
1121 {
1122 fReturnString = 1;
1123 port = scm_mkstrport (SCM_INUM0,
1124 scm_make_string (SCM_INUM0, SCM_UNDEFINED),
1125 SCM_OPN | SCM_WRTNG,
1126 FUNC_NAME);
1127 destination = port;
1128 }
1129 else
1130 {
1131 SCM_VALIDATE_OPORT_VALUE (1, destination);
1132 port = SCM_COERCE_OUTPORT (destination);
1133 }
1134 SCM_VALIDATE_STRING (2, message);
1135 SCM_VALIDATE_REST_ARGUMENT (args);
1136
1137 p = 0;
1138 start = 0;
1139 end = scm_i_string_length (message);
1140 for (p = start; p != end; ++p)
1141 if (scm_i_string_ref (message, p) == '~')
1142 {
1143 if (++p == end)
1144 break;
1145
1146 switch (scm_i_string_ref (message, p))
1147 {
1148 case 'A': case 'a':
1149 writingp = 0;
1150 break;
1151 case 'S': case 's':
1152 writingp = 1;
1153 break;
1154 case '~':
1155 scm_lfwrite_substr (message, start, p, port);
1156 start = p + 1;
1157 continue;
1158 case '%':
1159 scm_lfwrite_substr (message, start, p - 1, port);
1160 scm_newline (port);
1161 start = p + 1;
1162 continue;
1163 default:
1164 SCM_MISC_ERROR ("FORMAT: Unsupported format option ~~~A - use (ice-9 format) instead",
1165 scm_list_1 (SCM_MAKE_CHAR (scm_i_string_ref (message, p))));
1166
1167 }
1168
1169
1170 if (!scm_is_pair (args))
1171 SCM_MISC_ERROR ("FORMAT: Missing argument for ~~~A",
1172 scm_list_1 (SCM_MAKE_CHAR (scm_i_string_ref (message, p))));
1173
1174 scm_lfwrite_substr (message, start, p - 1, port);
1175 /* we pass destination here */
1176 scm_prin1 (SCM_CAR (args), destination, writingp);
1177 args = SCM_CDR (args);
1178 start = p + 1;
1179 }
1180
1181 scm_lfwrite_substr (message, start, p, port);
1182 if (!scm_is_eq (args, SCM_EOL))
1183 SCM_MISC_ERROR ("FORMAT: ~A superfluous arguments",
1184 scm_list_1 (scm_length (args)));
1185
1186 if (fReturnString)
1187 answer = scm_strport_to_string (destination);
1188
1189 return scm_return_first (answer, message);
1190 }
1191 #undef FUNC_NAME
1192
1193
1194 SCM_DEFINE (scm_newline, "newline", 0, 1, 0,
1195 (SCM port),
1196 "Send a newline to @var{port}.\n"
1197 "If @var{port} is omitted, send to the current output port.")
1198 #define FUNC_NAME s_scm_newline
1199 {
1200 if (SCM_UNBNDP (port))
1201 port = scm_current_output_port ();
1202
1203 SCM_VALIDATE_OPORT_VALUE (1, port);
1204
1205 scm_putc ('\n', SCM_COERCE_OUTPORT (port));
1206 return SCM_UNSPECIFIED;
1207 }
1208 #undef FUNC_NAME
1209
1210 SCM_DEFINE (scm_write_char, "write-char", 1, 1, 0,
1211 (SCM chr, SCM port),
1212 "Send character @var{chr} to @var{port}.")
1213 #define FUNC_NAME s_scm_write_char
1214 {
1215 if (SCM_UNBNDP (port))
1216 port = scm_current_output_port ();
1217
1218 SCM_VALIDATE_CHAR (1, chr);
1219 SCM_VALIDATE_OPORT_VALUE (2, port);
1220
1221 scm_putc ((int) SCM_CHAR (chr), SCM_COERCE_OUTPORT (port));
1222 #if 0
1223 #ifdef HAVE_PIPE
1224 # ifdef EPIPE
1225 if (EPIPE == errno)
1226 scm_close_port (port);
1227 # endif
1228 #endif
1229 #endif
1230 return SCM_UNSPECIFIED;
1231 }
1232 #undef FUNC_NAME
1233
1234 \f
1235
1236 /* Call back to Scheme code to do the printing of special objects
1237 * (like structs). SCM_PRINTER_APPLY applies PROC to EXP and a smob
1238 * containing PORT and PSTATE. This object can be used as the port for
1239 * display/write etc to continue the current print chain. The REVEALED
1240 * field of PSTATE is set to true to indicate that the print state has
1241 * escaped to Scheme and thus has to be freed by the GC.
1242 */
1243
1244 scm_t_bits scm_tc16_port_with_ps;
1245
1246 /* Print exactly as the port itself would */
1247
1248 static int
1249 port_with_ps_print (SCM obj, SCM port, scm_print_state *pstate)
1250 {
1251 obj = SCM_PORT_WITH_PS_PORT (obj);
1252 return scm_ptobs[SCM_PTOBNUM (obj)].print (obj, port, pstate);
1253 }
1254
1255 SCM
1256 scm_printer_apply (SCM proc, SCM exp, SCM port, scm_print_state *pstate)
1257 {
1258 pstate->revealed = 1;
1259 return scm_call_2 (proc, exp,
1260 scm_i_port_with_print_state (port, pstate->handle));
1261 }
1262
1263 SCM_DEFINE (scm_port_with_print_state, "port-with-print-state", 1, 1, 0,
1264 (SCM port, SCM pstate),
1265 "Create a new port which behaves like @var{port}, but with an\n"
1266 "included print state @var{pstate}. @var{pstate} is optional.\n"
1267 "If @var{pstate} isn't supplied and @var{port} already has\n"
1268 "a print state, the old print state is reused.")
1269 #define FUNC_NAME s_scm_port_with_print_state
1270 {
1271 SCM_VALIDATE_OPORT_VALUE (1, port);
1272 if (!SCM_UNBNDP (pstate))
1273 SCM_VALIDATE_PRINTSTATE (2, pstate);
1274 return scm_i_port_with_print_state (port, pstate);
1275 }
1276 #undef FUNC_NAME
1277
1278 SCM_DEFINE (scm_get_print_state, "get-print-state", 1, 0, 0,
1279 (SCM port),
1280 "Return the print state of the port @var{port}. If @var{port}\n"
1281 "has no associated print state, @code{#f} is returned.")
1282 #define FUNC_NAME s_scm_get_print_state
1283 {
1284 if (SCM_PORT_WITH_PS_P (port))
1285 return SCM_PORT_WITH_PS_PS (port);
1286 if (SCM_OUTPUT_PORT_P (port))
1287 return SCM_BOOL_F;
1288 SCM_WRONG_TYPE_ARG (1, port);
1289 }
1290 #undef FUNC_NAME
1291
1292 \f
1293
1294 void
1295 scm_init_print ()
1296 {
1297 SCM vtable, layout, type;
1298
1299 scm_init_opts (scm_print_options, scm_print_opts);
1300
1301 scm_print_options (scm_list_4 (scm_from_locale_symbol ("highlight-prefix"),
1302 scm_from_locale_string ("{"),
1303 scm_from_locale_symbol ("highlight-suffix"),
1304 scm_from_locale_string ("}")));
1305
1306 scm_gc_register_root (&print_state_pool);
1307 scm_gc_register_root (&scm_print_state_vtable);
1308 vtable = scm_make_vtable_vtable (scm_nullstr, SCM_INUM0, SCM_EOL);
1309 layout =
1310 scm_make_struct_layout (scm_from_locale_string (SCM_PRINT_STATE_LAYOUT));
1311 type = scm_make_struct (vtable, SCM_INUM0, scm_list_1 (layout));
1312 scm_set_struct_vtable_name_x (type, scm_from_locale_symbol ("print-state"));
1313 scm_print_state_vtable = type;
1314
1315 /* Don't want to bind a wrapper class in GOOPS, so pass 0 as arg1. */
1316 scm_tc16_port_with_ps = scm_make_smob_type (0, 0);
1317 scm_set_smob_print (scm_tc16_port_with_ps, port_with_ps_print);
1318
1319 #include "libguile/print.x"
1320
1321 scm_print_opts[SCM_PRINT_KEYWORD_STYLE_I].val = SCM_UNPACK (sym_reader);
1322 }
1323
1324 /*
1325 Local Variables:
1326 c-file-style: "gnu"
1327 End:
1328 */