]> git.donarmstrong.com Git - lilypond.git/blob - lily/lily-guile.cc
2003 -> 2004
[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", 1,0, 0,
106           (SCM name),
107           "Read the file named @var{name}, and return its contents in a string. The "
108 " file is looked up using the lilypond 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 a -1, 0 or 1, where -1 represents "
162           "left or down and 1 represents right or up. ")
163 {
164   if (gh_number_p (s))
165     {
166       int i = gh_scm2int (s);
167       return (i>= -1 && i <= 1)  ? SCM_BOOL_T : SCM_BOOL_F; 
168     }
169   return SCM_BOOL_F;
170 }
171
172 bool
173 is_number_pair (SCM p)
174 {
175   return gh_pair_p (p) && gh_number_p (ly_car (p)) && gh_number_p (ly_cdr (p));
176 }
177
178 typedef void (*Void_fptr) ();
179 Array<Void_fptr> *scm_init_funcs_;
180
181 void add_scm_init_func (void (*f) ())
182 {
183   if (!scm_init_funcs_)
184     scm_init_funcs_ = new Array<Void_fptr>;
185
186   scm_init_funcs_->push (f);
187 }
188
189
190 void
191 ly_init_ly_module (void *)
192 {
193   for (int i=scm_init_funcs_->size () ; i--;)
194     (scm_init_funcs_->elem (i)) ();
195
196   if (verbose_global_b)
197     progress_indication ("\n");
198   
199   scm_primitive_load_path (scm_makfrom0str ("lily.scm"));
200 }
201
202
203 SCM lily_module ;
204
205 void
206 ly_init_guile ()
207 {
208   lily_module = scm_c_define_module ("lily", ly_init_ly_module, 0);
209   scm_c_use_module ("lily");
210 }
211
212 unsigned int ly_scm_hash (SCM s)
213 {
214   return scm_ihashv (s, ~1u);
215 }
216
217
218
219 bool
220 is_direction (SCM s)
221 {
222   if (gh_number_p (s))
223     {
224       int i = gh_scm2int (s);
225       return i>= -1 && i <= 1; 
226     }
227   return false;
228 }
229
230
231 bool
232 is_axis (SCM s)
233 {
234   if (gh_number_p (s))
235     {
236       int i = gh_scm2int (s);
237       return i== 0 || i == 1;
238     }
239   return false;
240 }
241
242
243 Direction
244 to_dir (SCM s)
245 {
246   return SCM_INUMP (s) ?  (Direction) gh_scm2int (s) : CENTER;
247 }
248
249 Interval
250 ly_scm2interval (SCM p)
251 {
252   return  Interval (gh_scm2double (ly_car (p)),
253                     gh_scm2double (ly_cdr (p)));
254 }
255
256 Drul_array<Real>
257 ly_scm2realdrul (SCM p)
258 {
259   return  Drul_array<Real> (gh_scm2double (ly_car (p)),
260                             gh_scm2double (ly_cdr (p)));
261 }
262
263 SCM
264 ly_interval2scm (Drul_array<Real> i)
265 {
266   return gh_cons (gh_double2scm (i[LEFT]),
267                   gh_double2scm (i[RIGHT]));
268 }
269
270
271
272
273 bool
274 to_boolean (SCM s)
275 {
276   return gh_boolean_p (s) && gh_scm2bool (s);
277 }
278
279 /*
280   Appendable list L: the cdr contains the list, the car the last cons
281   in the list.
282  */
283 SCM
284 appendable_list ()
285 {
286   SCM s = gh_cons (SCM_EOL, SCM_EOL);
287   gh_set_car_x (s, s);
288   
289   return s;
290 }
291
292 void
293 appendable_list_append (SCM l, SCM elt)
294 {
295   SCM newcons = gh_cons (elt, SCM_EOL);
296   
297   gh_set_cdr_x (ly_car (l), newcons);      
298   gh_set_car_x (l, newcons);
299 }
300
301
302 SCM
303 ly_offset2scm (Offset o)
304 {
305   return gh_cons (gh_double2scm (o[X_AXIS]), gh_double2scm (o[Y_AXIS]));
306 }
307
308 Offset
309 ly_scm2offset (SCM s)
310 {
311   return Offset (gh_scm2double (ly_car (s)),
312                  gh_scm2double (ly_cdr (s)));
313 }
314
315    
316 LY_DEFINE(ly_number2string,  "ly:number->string", 1, 0,0,
317           (SCM s),
318           " converts @var{num} to a string without generating many decimals. It "
319 "leaves a space at the end.")
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, "%8.4f ", r);
336     }
337   else
338     {
339       sprintf (str, "%d ", gh_scm2int (s));
340     }
341
342   return scm_makfrom0str (str);
343 }
344
345 /*
346   Undef this to see if GUILE GC is causing too many swaps.
347  */
348
349 //#define TEST_GC
350
351 #ifdef TEST_GC
352 #include <libguile/gc.h>
353
354 static void *
355 greet_sweep (void *dummy1, void *dummy2, void *dummy3)
356 {
357    fprintf (stderr, "entering sweep\n");
358 }
359
360 static void *
361 wave_sweep_goodbye (void *dummy1, void *dummy2, void *dummy3)
362 {
363    fprintf (stderr, "leaving sweep\n");
364 }
365 #endif
366
367
368 #include "version.hh"
369 LY_DEFINE(ly_version,  "ly:version", 0, 0, 0, (),
370           "Return the current lilypond version as a list, e.g. @code{(1 3 127 uu1)}. ")
371 {
372   char const* vs =  "\'(" MAJOR_VERSION " " MINOR_VERSION " "  PATCH_LEVEL " " MY_PATCH_LEVEL ")" ;
373   
374   return gh_eval_str ((char*)vs);
375 }
376
377 LY_DEFINE(ly_unit,  "ly:unit", 0, 0, 0, (),
378           "Return the unit used for lengths as a string.")
379 {
380   return scm_makfrom0str (INTERNAL_UNIT);
381 }
382
383
384
385 LY_DEFINE(ly_dimension_p,  "ly:dimension?", 1, 0, 0, (SCM d),
386           "Return @var{d} is a number. Used to distinguish length "
387           "variables from normal numbers.")
388 {
389   return scm_number_p (d);
390 }
391
392 static void
393 init_functions ()
394 {
395 #ifdef TEST_GC 
396   scm_c_hook_add (&scm_before_mark_c_hook, greet_sweep, 0, 0);
397   scm_c_hook_add (&scm_before_sweep_c_hook, wave_sweep_goodbye, 0, 0);
398 #endif
399 }
400
401 ADD_SCM_INIT_FUNC (funcs, init_functions);
402
403 SCM
404 ly_deep_copy (SCM src)
405 {
406   if (gh_pair_p (src))
407     {
408       return gh_cons (ly_deep_copy (ly_car (src)), ly_deep_copy (ly_cdr (src)));
409     }
410   else if (gh_vector_p (src))
411     {
412       int  l = SCM_VECTOR_LENGTH (src);
413       SCM nv = scm_c_make_vector (l, SCM_UNDEFINED);
414       for (int i  =0 ; i< l ; i++)
415         {
416           SCM si = gh_int2scm (i);
417           scm_vector_set_x (nv, si, ly_deep_copy (scm_vector_ref (src, si))); 
418         }
419     }
420   else
421     return src;
422
423   return src;
424 }
425
426
427
428
429 SCM
430 ly_assoc_chain (SCM key, SCM achain)
431 {
432   if (gh_pair_p (achain))
433     {
434       SCM handle = scm_assoc (key, ly_car (achain));
435       if (gh_pair_p (handle))
436         return handle;
437       else
438         return ly_assoc_chain (key, ly_cdr (achain));
439     }
440   else
441     return SCM_BOOL_F;
442 }
443
444 /* looks the key up in the cdrs of the alist-keys
445    - ignoring the car and ignoring non-pair keys.
446    Returns first match found, i.e.
447
448    alist = ((1 . 10)
449                    ((1 . 2) . 11)
450                    ((2 . 1) . 12)
451                    ((3 . 0) . 13)
452                    ((4 . 1) . 14) )
453
454 I would like (ly_assoc_cdr 1) to return 12 - because it's the first
455 element with the cdr of the key = 1.  In other words (alloc_cdr key)
456 corresponds to call
457
458 (alloc (anything . key))
459
460
461
462 */
463 SCM
464 ly_assoc_cdr (SCM key, SCM alist)
465 {
466   if (gh_pair_p (alist)) {
467     SCM trykey = ly_caar(alist);
468     if(gh_pair_p(trykey) && to_boolean(scm_equal_p(key,ly_cdr(trykey))))
469       return ly_car(alist);
470     else
471       return ly_assoc_cdr (key, ly_cdr (alist));
472   }
473   else
474     return SCM_BOOL_F;
475 }
476
477 /*
478   LIST has the form "sym1 sym2 sym3\nsym4\nsym5"
479
480   i.e. \n and ' ' can be used interchangeably as separators.
481  */
482 SCM
483 parse_symbol_list (const char * list)
484 {
485   char * s = strdup (list);
486   char *orig = s;
487   SCM create_list = SCM_EOL;
488
489   char * e = s + strlen (s) - 1;
490   while (e >= s && isspace (*e))
491     *e -- = 0;
492
493   for (char * p = s; *p; p++)
494     {
495       if (*p == '\n')
496         *p = ' ' ;
497     }
498   
499   if (!s[0] )
500     s = 0;
501
502
503   
504   while (s)
505     {
506       char *next = strchr (s, ' ');
507       if (next)
508         *next++ = 0;
509
510       create_list = gh_cons (ly_symbol2scm (s), create_list);
511       s = next;
512     }
513
514   free (orig);
515   return create_list;
516 }
517
518
519 SCM
520 ly_truncate_list (int k, SCM l )
521 {
522   if (k == 0)
523     {
524       l = SCM_EOL;
525     }
526   else
527     {
528       SCM s = l;
529       k--;
530       for (; gh_pair_p (s) && k--; s = ly_cdr (s))
531         ;
532
533       if (gh_pair_p (s))
534         {
535           gh_set_cdr_x (s, SCM_EOL);
536         }
537     }
538   return l;
539 }
540
541
542 String
543 print_scm_val (SCM val)
544 {
545   String realval = ly_scm2string (ly_write2scm (val));
546   if (realval.length () > 200)
547     realval = realval.left_string (100) + "\n :\n :\n" + realval.right_string (100);
548   
549   return realval;        
550 }
551
552 bool
553 type_check_assignment (SCM sym, SCM val,  SCM type_symbol) 
554 {
555   bool ok = true;
556
557   /*
558     Always succeeds.
559
560
561     TODO: should remove #f from allowed vals?
562    */
563   if (val == SCM_EOL || val == SCM_BOOL_F)
564     return ok;
565
566   if (!gh_symbol_p (sym))
567 #if 0
568     return false;
569 #else
570   /*
571     This is used for autoBeamSettings.
572
573     TODO: deprecate the use of \override and \revert for
574     autoBeamSettings?
575
576     or use a symbol autoBeamSettingS?  
577    */
578   return true; 
579 #endif
580   
581   SCM type = scm_object_property (sym, type_symbol);
582
583   if (type != SCM_EOL && !gh_procedure_p (type))
584       {
585         warning (_f ("Can't find property type-check for `%s' (%s).",
586                      ly_symbol2string (sym).to_str0 (),
587                      ly_symbol2string (type_symbol).to_str0 ())
588                  + "  " + _ ("Perhaps you made a typing error?"));
589
590         /* Be strict when being anal :) */
591         if (internal_type_checking_global_b)
592           abort ();
593         
594         warning (_ ("Doing assignment anyway."));
595       }
596   else
597     {
598       if (val != SCM_EOL
599           && gh_procedure_p (type)
600           && gh_call1 (type, val) == SCM_BOOL_F)
601         {
602           SCM errport = scm_current_error_port ();
603           ok = false;
604           SCM typefunc = scm_primitive_eval (ly_symbol2scm ("type-name"));
605           SCM type_name = gh_call1 (typefunc, type);
606
607          
608           scm_puts (_f ("Type check for `%s' failed; value `%s' must be of type `%s'",
609                         ly_symbol2string (sym).to_str0 (),
610                         print_scm_val (val),
611                         ly_scm2string (type_name).to_str0 ()).to_str0 (),
612                     errport);
613           scm_puts ("\n", errport);                   
614         }
615     }
616   return ok;
617 }
618
619
620 /* some SCM abbrevs
621
622    zijn deze nou handig?
623    zijn ze er al in scheme, maar heten ze anders? */
624
625
626 /* Remove doubles from (sorted) list */
627 SCM
628 ly_unique (SCM list)
629 {
630   SCM unique = SCM_EOL;
631   for (SCM i = list; gh_pair_p (i); i = ly_cdr (i))
632     {
633       if (!gh_pair_p (ly_cdr (i))
634           || !gh_equal_p (ly_car (i), ly_cadr (i)))
635         unique = gh_cons (ly_car (i), unique);
636     }
637   return scm_reverse_x (unique, SCM_EOL);
638 }
639
640 /* tail add */
641 SCM
642 ly_snoc (SCM s, SCM list)
643 {
644   return gh_append2 (list, scm_list_n (s, SCM_UNDEFINED));
645 }
646
647
648 /* Split list at member s, removing s.
649    Return (BEFORE . AFTER) */
650 SCM
651 ly_split_list (SCM s, SCM list)
652 {
653   SCM before = SCM_EOL;
654   SCM after = list;
655   for (; gh_pair_p (after);)
656     {
657       SCM i = ly_car (after);
658       after = ly_cdr (after);
659       if (gh_equal_p (i, s))
660         break;
661       before = gh_cons (i, before);
662     }
663   return gh_cons ( scm_reverse_x (before, SCM_EOL),  after);
664   
665 }
666
667
668 void
669 taint (SCM *)
670 {
671   /*
672     nop.
673    */
674 }
675
676 /*
677   display stuff without using stack
678  */
679 SCM
680 display_list (SCM s)
681 {
682   SCM p = scm_current_output_port();
683
684   scm_puts ("(", p);
685   for (; gh_pair_p(s); s =gh_cdr(s))
686     {
687       scm_display (gh_car(s), p);
688       scm_puts (" ", p);      
689     }
690   scm_puts (")", p);
691   return SCM_UNSPECIFIED;
692 }
693
694 Slice
695 int_list_to_slice (SCM l)
696 {
697   Slice s;
698   s.set_empty ();
699   for (; gh_pair_p (l); l = gh_cdr (l))
700     {
701       if (gh_number_p (gh_car (l)))
702         s.add_point (gh_scm2int (gh_car (l))); 
703     }
704
705   return s;
706 }
707
708
709 /*
710   Return I-th element, or last elt L. If I < 0, then we take the first
711   element.
712
713   PRE: length (L) > 0
714  */
715 SCM
716 robust_list_ref(int i, SCM l)
717 {
718   while (i-- > 0 && gh_pair_p (gh_cdr(l)))
719     l = gh_cdr (l);
720
721   return gh_car(l);
722 }
723
724
725
726 Real
727 robust_scm2double (SCM k, double x)
728 {
729   if (gh_number_p (k))
730     x = gh_scm2double (k);
731   return x;
732 }
733
734 Interval
735 robust_scm2interval (SCM k, Drul_array<Real> v)
736 {
737   Interval i;
738   i[LEFT]= v[LEFT];
739   i[RIGHT]= v[RIGHT];
740   if (is_number_pair (k))
741     i = ly_scm2interval (k);
742   return i;
743 }
744
745 Drul_array<Real>
746 robust_scm2drul (SCM k, Drul_array<Real> v)
747 {
748   if (is_number_pair (k))
749     v = ly_scm2interval (k);
750   return v;
751 }
752
753 Offset
754 robust_scm2offset (SCM k, Offset o)
755 {
756   if (is_number_pair (k))
757     o = ly_scm2offset (k);
758
759   return o;
760 }
761
762
763 int
764 robust_scm2int (SCM k, int o)
765 {
766   if (scm_integer_p (k) == SCM_BOOL_T)
767     o = gh_scm2int (k);
768
769   return o;
770 }
771
772
773 SCM
774 alist_to_hashq (SCM alist)
775 {
776   int i = scm_ilength (alist);
777   if (i < 0)
778     return scm_make_vector (gh_int2scm (0), SCM_EOL);
779           
780   SCM tab = scm_make_vector (gh_int2scm (i), SCM_EOL);
781   for (SCM s = alist; gh_pair_p (s); s = ly_cdr (s))
782     {
783       SCM pt = ly_cdar (s);
784       scm_hashq_set_x (tab, ly_caar (s), pt);
785     }
786   return tab; 
787 }