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