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