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