]> git.donarmstrong.com Git - lilypond.git/blob - lily/lily-guile.cc
* lily/lily-guile.cc (ly:number->string): Do not leave space at
[lilypond.git] / lily / lily-guile.cc
1 /*
2   lily-guile.cc -- implement assorted guile functions
3
4   source file of the GNU LilyPond music typesetter
5
6   (c) 1998--2004 Jan Nieuwenhuizen <janneke@gnu.org>
7
8   Han-Wen Nienhuys <hanwen@cs.uu.nl>
9 */
10
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <math.h>   /* isinf */
15 #include <string.h> /* strdup, strchr */
16 #include <ctype.h>
17
18 #include "lily-proto.hh"
19
20 /* macosx fix:
21
22
23  source-file.hh includes cmath which undefines isinf and isnan
24 */
25 inline int my_isinf (Real r) { return isinf (r); }
26 inline int my_isnan (Real r) { return isnan (r); }
27
28
29
30 #include "libc-extension.hh"
31 #include "lily-guile.hh"
32 #include "main.hh"
33 #include "file-path.hh"
34 #include "warn.hh"
35 #include "direction.hh"
36 #include "offset.hh"
37 #include "interval.hh"
38 #include "pitch.hh"
39 #include "dimensions.hh"
40 #include "source-file.hh"
41
42 // #define TEST_GC
43
44 SCM
45 ly_last (SCM list)
46 {
47   return ly_car (scm_last_pair (list));
48 }
49
50
51 SCM
52 ly_write2scm (SCM s)
53 {
54   SCM port = scm_mkstrport (SCM_INUM0, 
55                             scm_make_string (SCM_INUM0, SCM_UNDEFINED),
56                             SCM_OPN | SCM_WRTNG,
57                             "ly_write2string");
58   //  SCM write = scm_eval_3 (ly_symbol2scm ("write"), s, SCM_EOL);
59   SCM write = scm_primitive_eval (ly_symbol2scm ("write"));
60   
61   // scm_apply (write, port, SCM_EOL);
62   gh_call2 (write, s, port);
63   return scm_strport_to_string (port);
64 }
65
66
67 SCM
68 ly_quote_scm (SCM s)
69 {
70   return scm_list_n (ly_symbol2scm ("quote"), s, SCM_UNDEFINED);
71 }
72
73 String
74 ly_symbol2string (SCM s)
75 {
76   assert (gh_symbol_p (s));
77   return String ((Byte*)SCM_STRING_CHARS (s), (int) SCM_STRING_LENGTH (s));
78 }
79
80 String
81 gulp_file_to_string (String fn)
82 {
83   String s = global_path.find (fn);
84   if (s == "")
85     {
86       String e = _f ("can't find file: `%s'", fn);
87       e += " ";
88       e += _f ("(load path: `%s')", global_path.to_string ());
89       error (e);
90     }
91   else if (verbose_global_b)
92     progress_indication ("[" + s);
93
94   int n;
95   char * str = gulp_file (s, &n);
96   String result (str);
97   delete[] str;
98   
99   if (verbose_global_b)
100     progress_indication ("]");
101
102   return result;
103 }
104
105 LY_DEFINE (ly_gulp_file, "ly:gulp-file",
106            1, 0, 0, (SCM name),
107           "Read the file @var{name}, and return its contents in a string.  "
108            "The file is looked up using the search path.")
109 {
110   return scm_makfrom0str (gulp_file_to_string (ly_scm2string (name)).to_str0 ());
111 }
112
113
114 extern "C" {
115   // maybe gdb 5.0 becomes quicker if it doesn't do fancy C++ typing?
116 void
117 ly_display_scm (SCM s)
118 {
119   gh_display (s);
120   gh_newline ();
121 }
122 };
123
124 String
125 ly_scm2string (SCM s)
126 {
127   assert (gh_string_p (s));
128
129   char *p = SCM_STRING_CHARS (s);
130   String r (p);
131   return r;
132 }
133
134 SCM
135 index_get_cell (SCM s, Direction d)
136 {
137   
138   assert (d);
139   return (d == LEFT) ? ly_car (s) : ly_cdr (s);
140 }
141
142 SCM
143 index_set_cell (SCM s, Direction d, SCM v)
144 {
145   if (d == LEFT)
146     gh_set_car_x (s, v);
147   else if (d == RIGHT)
148     gh_set_cdr_x (s, v);
149   return s;
150 }
151   
152 LY_DEFINE (ly_warning,"ly:warn", 1, 0, 0,
153   (SCM str),"Scheme callable function to issue the warning @code{msg}.")
154 {
155   SCM_ASSERT_TYPE (gh_string_p (str), str, SCM_ARG1, __FUNCTION__, "string");
156   warning ("lily-guile: " + ly_scm2string (str));
157   return SCM_BOOL_T;
158 }
159
160 LY_DEFINE (ly_dir_p,  "ly:dir?", 1,0, 0,  (SCM s),
161           "type predicate. A direction is @code{-1}, @code{0} or "
162            "@code{1}, where @code{-1} represents "
163           "left or down and @code{1} represents right or up.")
164 {
165   if (gh_number_p (s))
166     {
167       int i = gh_scm2int (s);
168       return (i>= -1 && i <= 1)  ? SCM_BOOL_T : SCM_BOOL_F; 
169     }
170   return SCM_BOOL_F;
171 }
172
173 bool
174 is_number_pair (SCM p)
175 {
176   return gh_pair_p (p) && gh_number_p (ly_car (p)) && gh_number_p (ly_cdr (p));
177 }
178
179 typedef void (*Void_fptr) ();
180 Array<Void_fptr> *scm_init_funcs_;
181
182 void add_scm_init_func (void (*f) ())
183 {
184   if (!scm_init_funcs_)
185     scm_init_funcs_ = new Array<Void_fptr>;
186
187   scm_init_funcs_->push (f);
188 }
189
190
191 void
192 ly_init_ly_module (void *)
193 {
194   for (int i=scm_init_funcs_->size () ; i--;)
195     (scm_init_funcs_->elem (i)) ();
196
197   if (verbose_global_b)
198     progress_indication ("\n");
199   
200   scm_primitive_load_path (scm_makfrom0str ("lily.scm"));
201 }
202
203
204 SCM global_lily_module;
205
206 void
207 ly_init_guile ()
208 {
209   global_lily_module = scm_c_define_module ("lily", ly_init_ly_module, 0);
210   scm_c_use_module ("lily");
211 }
212
213 unsigned int ly_scm_hash (SCM s)
214 {
215   return scm_ihashv (s, ~1u);
216 }
217
218
219
220 bool
221 is_direction (SCM s)
222 {
223   if (gh_number_p (s))
224     {
225       int i = gh_scm2int (s);
226       return i>= -1 && i <= 1; 
227     }
228   return false;
229 }
230
231
232 bool
233 is_axis (SCM s)
234 {
235   if (gh_number_p (s))
236     {
237       int i = gh_scm2int (s);
238       return i== 0 || i == 1;
239     }
240   return false;
241 }
242
243
244 Direction
245 to_dir (SCM s)
246 {
247   return SCM_INUMP (s) ?  (Direction) gh_scm2int (s) : CENTER;
248 }
249
250 Interval
251 ly_scm2interval (SCM p)
252 {
253   return  Interval (gh_scm2double (ly_car (p)),
254                     gh_scm2double (ly_cdr (p)));
255 }
256
257 Drul_array<Real>
258 ly_scm2realdrul (SCM p)
259 {
260   return  Drul_array<Real> (gh_scm2double (ly_car (p)),
261                             gh_scm2double (ly_cdr (p)));
262 }
263
264 SCM
265 ly_interval2scm (Drul_array<Real> i)
266 {
267   return gh_cons (gh_double2scm (i[LEFT]),
268                   gh_double2scm (i[RIGHT]));
269 }
270
271
272
273
274 bool
275 to_boolean (SCM s)
276 {
277   return gh_boolean_p (s) && gh_scm2bool (s);
278 }
279
280 /*
281   Appendable list L: the cdr contains the list, the car the last cons
282   in the list.
283  */
284 SCM
285 appendable_list ()
286 {
287   SCM s = gh_cons (SCM_EOL, SCM_EOL);
288   gh_set_car_x (s, s);
289   
290   return s;
291 }
292
293 void
294 appendable_list_append (SCM l, SCM elt)
295 {
296   SCM newcons = gh_cons (elt, SCM_EOL);
297   
298   gh_set_cdr_x (ly_car (l), newcons);      
299   gh_set_car_x (l, newcons);
300 }
301
302
303 SCM
304 ly_offset2scm (Offset o)
305 {
306   return gh_cons (gh_double2scm (o[X_AXIS]), gh_double2scm (o[Y_AXIS]));
307 }
308
309 Offset
310 ly_scm2offset (SCM s)
311 {
312   return Offset (gh_scm2double (ly_car (s)),
313                  gh_scm2double (ly_cdr (s)));
314 }
315
316    
317 LY_DEFINE (ly_number2string, "ly:number->string",
318            1, 0, 0, (SCM s),
319            "Convert @var{num} to a string without generating many decimals.")
320 {
321   SCM_ASSERT_TYPE (gh_number_p (s), s, SCM_ARG1, __FUNCTION__, "number");
322
323   char str[400];                        // ugh.
324
325   if (scm_exact_p (s) == SCM_BOOL_F)
326     {
327       Real r (gh_scm2double (s));
328
329       if (my_isinf (r) || my_isnan (r))
330         {
331           programming_error ("Infinity or NaN encountered while converting Real number; setting to zero.");
332           r = 0.0;
333         }
334
335       sprintf (str, "%08.4f", r);
336     }
337   else
338     sprintf (str, "%d", gh_scm2int (s));
339
340   return scm_makfrom0str (str);
341 }
342
343 /*
344   Undef this to see if GUILE GC is causing too many swaps.
345  */
346
347 //#define TEST_GC
348
349 #ifdef TEST_GC
350 #include <libguile/gc.h>
351
352 static void *
353 greet_sweep (void *dummy1, void *dummy2, void *dummy3)
354 {
355    fprintf (stderr, "entering sweep\n");
356 }
357
358 static void *
359 wave_sweep_goodbye (void *dummy1, void *dummy2, void *dummy3)
360 {
361    fprintf (stderr, "leaving sweep\n");
362 }
363 #endif
364
365
366 #include "version.hh"
367 LY_DEFINE (ly_version,  "ly:version", 0, 0, 0, (),
368           "Return the current lilypond version as a list, e.g. @code{(1 3 127 uu1)}. ")
369 {
370   char const* vs =  "\'(" MAJOR_VERSION " " MINOR_VERSION " "  PATCH_LEVEL " " MY_PATCH_LEVEL ")" ;
371   
372   return gh_eval_str ((char*)vs);
373 }
374
375 LY_DEFINE (ly_unit,  "ly:unit", 0, 0, 0, (),
376           "Return the unit used for lengths as a string.")
377 {
378   return scm_makfrom0str (INTERNAL_UNIT);
379 }
380
381
382
383 LY_DEFINE (ly_dimension_p,  "ly:dimension?", 1, 0, 0, (SCM d),
384           "Return @var{d} is a number. Used to distinguish length "
385           "variables from normal numbers.")
386 {
387   return scm_number_p (d);
388 }
389
390 static void
391 init_functions ()
392 {
393 #ifdef TEST_GC 
394   scm_c_hook_add (&scm_before_mark_c_hook, greet_sweep, 0, 0);
395   scm_c_hook_add (&scm_before_sweep_c_hook, wave_sweep_goodbye, 0, 0);
396 #endif
397 }
398
399 ADD_SCM_INIT_FUNC (funcs, init_functions);
400
401 SCM
402 ly_deep_copy (SCM src)
403 {
404   if (gh_pair_p (src))
405     {
406       return gh_cons (ly_deep_copy (ly_car (src)), ly_deep_copy (ly_cdr (src)));
407     }
408   else if (gh_vector_p (src))
409     {
410       int  l = SCM_VECTOR_LENGTH (src);
411       SCM nv = scm_c_make_vector (l, SCM_UNDEFINED);
412       for (int i  =0 ; i< l ; i++)
413         {
414           SCM si = gh_int2scm (i);
415           scm_vector_set_x (nv, si, ly_deep_copy (scm_vector_ref (src, si))); 
416         }
417     }
418   else
419     return src;
420
421   return src;
422 }
423
424
425
426
427 SCM
428 ly_assoc_chain (SCM key, SCM achain)
429 {
430   if (gh_pair_p (achain))
431     {
432       SCM handle = scm_assoc (key, ly_car (achain));
433       if (gh_pair_p (handle))
434         return handle;
435       else
436         return ly_assoc_chain (key, ly_cdr (achain));
437     }
438   else
439     return SCM_BOOL_F;
440 }
441
442 /* looks the key up in the cdrs of the alist-keys
443    - ignoring the car and ignoring non-pair keys.
444    Returns first match found, i.e.
445
446    alist = ((1 . 10)
447                    ((1 . 2) . 11)
448                    ((2 . 1) . 12)
449                    ((3 . 0) . 13)
450                    ((4 . 1) . 14) )
451
452 I would like (ly_assoc_cdr 1) to return 12 - because it's the first
453 element with the cdr of the key = 1.  In other words (alloc_cdr key)
454 corresponds to call
455
456 (alloc (anything . key))
457
458
459
460 */
461 SCM
462 ly_assoc_cdr (SCM key, SCM alist)
463 {
464   if (gh_pair_p (alist)) {
465     SCM trykey = ly_caar (alist);
466     if (gh_pair_p (trykey) && to_boolean (scm_equal_p (key,ly_cdr (trykey))))
467       return ly_car (alist);
468     else
469       return ly_assoc_cdr (key, ly_cdr (alist));
470   }
471   else
472     return SCM_BOOL_F;
473 }
474
475 /*
476   LIST has the form "sym1 sym2 sym3\nsym4\nsym5"
477
478   i.e. \n and ' ' can be used interchangeably as separators.
479  */
480 SCM
481 parse_symbol_list (const char * list)
482 {
483   char * s = strdup (list);
484   char *orig = s;
485   SCM create_list = SCM_EOL;
486
487   char * e = s + strlen (s) - 1;
488   while (e >= s && isspace (*e))
489     *e -- = 0;
490
491   for (char * p = s; *p; p++)
492     {
493       if (*p == '\n')
494         *p = ' ' ;
495     }
496   
497   if (!s[0] )
498     s = 0;
499
500
501   
502   while (s)
503     {
504       char *next = strchr (s, ' ');
505       if (next)
506         *next++ = 0;
507
508       create_list = gh_cons (ly_symbol2scm (s), create_list);
509       s = next;
510     }
511
512   free (orig);
513   return create_list;
514 }
515
516
517 SCM
518 ly_truncate_list (int k, SCM l )
519 {
520   if (k == 0)
521     {
522       l = SCM_EOL;
523     }
524   else
525     {
526       SCM s = l;
527       k--;
528       for (; gh_pair_p (s) && k--; s = ly_cdr (s))
529         ;
530
531       if (gh_pair_p (s))
532         {
533           gh_set_cdr_x (s, SCM_EOL);
534         }
535     }
536   return l;
537 }
538
539
540 String
541 print_scm_val (SCM val)
542 {
543   String realval = ly_scm2string (ly_write2scm (val));
544   if (realval.length () > 200)
545     realval = realval.left_string (100) + "\n :\n :\n" + realval.right_string (100);
546   
547   return realval;        
548 }
549
550 bool
551 type_check_assignment (SCM sym, SCM val,  SCM type_symbol) 
552 {
553   bool ok = true;
554
555   /*
556     Always succeeds.
557
558
559     TODO: should remove #f from allowed vals?
560    */
561   if (val == SCM_EOL || val == SCM_BOOL_F)
562     return ok;
563
564   if (!gh_symbol_p (sym))
565 #if 0
566     return false;
567 #else
568   /*
569     This is used for autoBeamSettings.
570
571     TODO: deprecate the use of \override and \revert for
572     autoBeamSettings?
573
574     or use a symbol autoBeamSettingS?  
575    */
576   return true; 
577 #endif
578   
579   SCM type = scm_object_property (sym, type_symbol);
580
581   if (type != SCM_EOL && !gh_procedure_p (type))
582       {
583         warning (_f ("Can't find property type-check for `%s' (%s).",
584                      ly_symbol2string (sym).to_str0 (),
585                      ly_symbol2string (type_symbol).to_str0 ())
586                  + "  " + _ ("Perhaps you made a typing error?"));
587
588         /* Be strict when being anal :) */
589         if (internal_type_checking_global_b)
590           abort ();
591         
592         warning (_ ("Doing assignment anyway."));
593       }
594   else
595     {
596       if (val != SCM_EOL
597           && gh_procedure_p (type)
598           && gh_call1 (type, val) == SCM_BOOL_F)
599         {
600           SCM errport = scm_current_error_port ();
601           ok = false;
602           SCM typefunc = scm_primitive_eval (ly_symbol2scm ("type-name"));
603           SCM type_name = gh_call1 (typefunc, type);
604
605          
606           scm_puts (_f ("Type check for `%s' failed; value `%s' must be of type `%s'",
607                         ly_symbol2string (sym).to_str0 (),
608                         print_scm_val (val),
609                         ly_scm2string (type_name).to_str0 ()).to_str0 (),
610                     errport);
611           scm_puts ("\n", errport);                   
612         }
613     }
614   return ok;
615 }
616
617
618 /* some SCM abbrevs
619
620    zijn deze nou handig?
621    zijn ze er al in scheme, maar heten ze anders? */
622
623
624 /* Remove doubles from (sorted) list */
625 SCM
626 ly_unique (SCM list)
627 {
628   SCM unique = SCM_EOL;
629   for (SCM i = list; gh_pair_p (i); i = ly_cdr (i))
630     {
631       if (!gh_pair_p (ly_cdr (i))
632           || !gh_equal_p (ly_car (i), ly_cadr (i)))
633         unique = gh_cons (ly_car (i), unique);
634     }
635   return scm_reverse_x (unique, SCM_EOL);
636 }
637
638 /* tail add */
639 SCM
640 ly_snoc (SCM s, SCM list)
641 {
642   return gh_append2 (list, scm_list_n (s, SCM_UNDEFINED));
643 }
644
645
646 /* Split list at member s, removing s.
647    Return (BEFORE . AFTER) */
648 SCM
649 ly_split_list (SCM s, SCM list)
650 {
651   SCM before = SCM_EOL;
652   SCM after = list;
653   for (; gh_pair_p (after);)
654     {
655       SCM i = ly_car (after);
656       after = ly_cdr (after);
657       if (gh_equal_p (i, s))
658         break;
659       before = gh_cons (i, before);
660     }
661   return gh_cons ( scm_reverse_x (before, SCM_EOL),  after);
662   
663 }
664
665
666 void
667 taint (SCM *)
668 {
669   /*
670     nop.
671    */
672 }
673
674 /*
675   display stuff without using stack
676  */
677 SCM
678 display_list (SCM s)
679 {
680   SCM p = scm_current_output_port ();
681
682   scm_puts ("(", p);
683   for (; gh_pair_p (s); s =gh_cdr (s))
684     {
685       scm_display (gh_car (s), p);
686       scm_puts (" ", p);      
687     }
688   scm_puts (")", p);
689   return SCM_UNSPECIFIED;
690 }
691
692 Slice
693 int_list_to_slice (SCM l)
694 {
695   Slice s;
696   s.set_empty ();
697   for (; gh_pair_p (l); l = gh_cdr (l))
698     {
699       if (gh_number_p (gh_car (l)))
700         s.add_point (gh_scm2int (gh_car (l))); 
701     }
702
703   return s;
704 }
705
706
707 /*
708   Return I-th element, or last elt L. If I < 0, then we take the first
709   element.
710
711   PRE: length (L) > 0
712  */
713 SCM
714 robust_list_ref (int i, SCM l)
715 {
716   while (i-- > 0 && gh_pair_p (gh_cdr (l)))
717     l = gh_cdr (l);
718
719   return gh_car (l);
720 }
721
722
723
724 Real
725 robust_scm2double (SCM k, double x)
726 {
727   if (gh_number_p (k))
728     x = gh_scm2double (k);
729   return x;
730 }
731
732 Interval
733 robust_scm2interval (SCM k, Drul_array<Real> v)
734 {
735   Interval i;
736   i[LEFT]= v[LEFT];
737   i[RIGHT]= v[RIGHT];
738   if (is_number_pair (k))
739     i = ly_scm2interval (k);
740   return i;
741 }
742
743 Drul_array<Real>
744 robust_scm2drul (SCM k, Drul_array<Real> v)
745 {
746   if (is_number_pair (k))
747     v = ly_scm2interval (k);
748   return v;
749 }
750
751 Offset
752 robust_scm2offset (SCM k, Offset o)
753 {
754   if (is_number_pair (k))
755     o = ly_scm2offset (k);
756
757   return o;
758 }
759
760
761 int
762 robust_scm2int (SCM k, int o)
763 {
764   if (scm_integer_p (k) == SCM_BOOL_T)
765     o = gh_scm2int (k);
766
767   return o;
768 }
769
770
771 SCM
772 alist_to_hashq (SCM alist)
773 {
774   int i = scm_ilength (alist);
775   if (i < 0)
776     return scm_make_vector (gh_int2scm (0), SCM_EOL);
777           
778   SCM tab = scm_make_vector (gh_int2scm (i), SCM_EOL);
779   for (SCM s = alist; gh_pair_p (s); s = ly_cdr (s))
780     {
781       SCM pt = ly_cdar (s);
782       scm_hashq_set_x (tab, ly_caar (s), pt);
783     }
784   return tab; 
785 }
786
787 #if 1
788 /*
789   Debugging mem leaks:
790  */
791 LY_DEFINE (ly_protects, "ly:protects", 0, 0, 0, (),
792           "Return hash of protected objects.")
793 {
794   return scm_protects;
795 }
796 #endif