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