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