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