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