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