]> git.donarmstrong.com Git - lilypond.git/blob - lily/lily-guile.cc
use SCM module in stead of
[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--2002 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
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
74
75 String
76 ly_symbol2string (SCM s)
77 {
78   assert (gh_symbol_p (s));
79   return String ((Byte*)SCM_STRING_CHARS (s), (int) SCM_STRING_LENGTH (s));
80 }
81
82
83 String
84 gulp_file_to_string (String fn)
85 {
86   String s = global_path.find (fn);
87   if (s == "")
88     {
89       String e = _f ("can't find file: `%s'", fn);
90       e += " ";
91       e += _f ("(load path: `%s')", global_path.string ());
92       error (e);
93     }
94   else if (verbose_global_b)
95     progress_indication ("[" + s);
96
97
98   int n;
99   char * str = gulp_file (s, &n);
100   String result (str);
101   delete[] str;
102   
103   if (verbose_global_b)
104     progress_indication ("]");
105
106   return result;
107 }
108
109 LY_DEFINE(ly_gulp_file, "ly-gulp-file", 1,0, 0,
110           (SCM name),
111           "Read the file named @var{name}, and return its contents in a string. The
112 file is looked up using the lilypond search path.
113
114 ")
115 {
116   return scm_makfrom0str (gulp_file_to_string (ly_scm2string (name)).to_str0 ());
117 }
118
119
120 extern "C" {
121   // maybe gdb 5.0 becomes quicker if it doesn't do fancy C++ typing?
122 void
123 ly_display_scm (SCM s)
124 {
125   gh_display (s);
126   gh_newline ();
127 }
128 };
129
130 String
131 ly_scm2string (SCM s)
132 {
133   assert (gh_string_p (s));
134
135   char *p = SCM_STRING_CHARS(s);
136   String r (p);
137   return r;
138 }
139
140 SCM
141 index_get_cell (SCM s, Direction d)
142 {
143   
144   assert (d);
145   return (d == LEFT) ? ly_car (s) : ly_cdr (s);
146 }
147
148 SCM
149 index_set_cell (SCM s, Direction d, SCM v)
150 {
151   if (d == LEFT)
152     gh_set_car_x (s, v);
153   else if (d == RIGHT)
154     gh_set_cdr_x (s, v);
155   return s;
156 }
157   
158 LY_DEFINE(ly_warning,"ly-warn", 1, 0, 0,
159   (SCM str),"Scheme callable function to issue the warning @code{msg}.")
160 {
161   SCM_ASSERT_TYPE (gh_string_p (str), str, SCM_ARG1, __FUNCTION__, "string");
162   warning ("lily-guile: " + ly_scm2string (str));
163   return SCM_BOOL_T;
164 }
165
166 LY_DEFINE(ly_isdir,  "dir?", 1,0, 0,  (SCM s),
167           "type predicate. A direction is a -1, 0 or 1, where -1 represents left or
168 down and 1 represents right or up.
169 ")
170 {
171   if (gh_number_p (s))
172     {
173       int i = gh_scm2int (s);
174       return (i>= -1 && i <= 1)  ? SCM_BOOL_T : SCM_BOOL_F; 
175     }
176   return SCM_BOOL_F;
177 }
178
179 bool
180 ly_number_pair_p (SCM p)
181 {
182   return gh_pair_p (p) && gh_number_p (ly_car (p)) && gh_number_p (ly_cdr (p));
183 }
184
185 typedef void (*Void_fptr) ();
186 Array<Void_fptr> *scm_init_funcs_;
187
188 void add_scm_init_func (void (*f) ())
189 {
190   if (!scm_init_funcs_)
191     scm_init_funcs_ = new Array<Void_fptr>;
192
193   scm_init_funcs_->push (f);
194 }
195
196
197 void
198 ly_init_guile ()
199 {
200   SCM last_mod = scm_current_module ();
201   scm_set_current_module (scm_c_resolve_module ("lily"));
202
203   scm_c_use_module ("guile");
204   
205   for (int i=scm_init_funcs_->size () ; i--;)
206     (scm_init_funcs_->elem (i)) ();
207
208   if (verbose_global_b)
209     progress_indication ("\n");
210
211
212   scm_primitive_load_path (scm_makfrom0str ("lily.scm"));
213
214   scm_set_current_module (last_mod);
215 }
216
217 unsigned int ly_scm_hash (SCM s)
218 {
219   return scm_ihashv (s, ~1u);
220 }
221
222
223
224 bool
225 ly_dir_p (SCM s)
226 {
227   if (gh_number_p (s))
228     {
229       int i = gh_scm2int (s);
230       return i>= -1 && i <= 1; 
231     }
232   return false;
233 }
234
235
236 bool
237 ly_axis_p (SCM s)
238 {
239   if (gh_number_p (s))
240     {
241       int i = gh_scm2int (s);
242       return i== 0 || i == 1;
243     }
244   return false;
245 }
246
247
248 Direction
249 to_dir (SCM s)
250 {
251   return SCM_INUMP (s) ?  (Direction) gh_scm2int (s) : CENTER;
252 }
253
254 Interval
255 ly_scm2interval (SCM p)
256 {
257   return  Interval (gh_scm2double (ly_car (p)),
258                     gh_scm2double (ly_cdr (p)));
259 }
260
261 SCM
262 ly_interval2scm (Drul_array<Real> i)
263 {
264   return gh_cons (gh_double2scm (i[LEFT]),
265                   gh_double2scm (i[RIGHT]));
266 }
267
268
269
270
271 bool
272 to_boolean (SCM s)
273 {
274   return gh_boolean_p (s) && gh_scm2bool (s);
275 }
276
277 /*
278   Appendable list L: the cdr contains the list, the car the last cons
279   in the list.
280  */
281 SCM
282 appendable_list ()
283 {
284   SCM s = gh_cons (SCM_EOL, SCM_EOL);
285   gh_set_car_x (s, s);
286   
287   return s;
288 }
289
290 void
291 appendable_list_append (SCM l, SCM elt)
292 {
293   SCM newcons = gh_cons (elt, SCM_EOL);
294   
295   gh_set_cdr_x (ly_car (l), newcons);      
296   gh_set_car_x (l, newcons);
297 }
298
299
300 SCM
301 ly_offset2scm (Offset o)
302 {
303   return gh_cons (gh_double2scm (o[X_AXIS]), gh_double2scm (o[Y_AXIS]));
304 }
305
306 Offset
307 ly_scm2offset (SCM s)
308 {
309   return Offset (gh_scm2double (ly_car (s)),
310                  gh_scm2double (ly_cdr (s)));
311 }
312
313    
314 LY_DEFINE(ly_number2string,  "ly-number->string", 1, 0,0,
315           (SCM s),
316           " converts @var{num} to a string without generating many decimals. It
317 leaves a space at the end.
318 ")
319 {
320   SCM_ASSERT_TYPE (gh_number_p (s), s, SCM_ARG1, __FUNCTION__, "number");
321
322   char str[400];                        // ugh.
323
324   if (scm_exact_p (s) == SCM_BOOL_F)
325     {
326       Real r (gh_scm2double (s));
327
328       if (my_isinf (r) || my_isnan (r))
329         {
330           programming_error ("Infinity or NaN encountered while converting Real number; setting to zero.");
331           r = 0.0;
332         }
333
334       sprintf (str, "%8.4f ", r);
335     }
336   else
337     {
338       sprintf (str, "%d ", gh_scm2int (s));
339     }
340
341   return scm_makfrom0str (str);
342 }
343
344 /*
345   Undef this to see if GUILE GC is causing too many swaps.
346  */
347
348 //#define TEST_GC
349
350 #ifdef TEST_GC
351 #include <libguile/gc.h>
352
353 static void *
354 greet_sweep (void *dummy1, void *dummy2, void *dummy3)
355 {
356    fprintf (stderr, "entering sweep\n");
357 }
358
359 static void *
360 wave_sweep_goodbye (void *dummy1, void *dummy2, void *dummy3)
361 {
362    fprintf (stderr, "leaving sweep\n");
363 }
364 #endif
365
366
367 #include "version.hh"
368 LY_DEFINE(ly_version,  "ly-version", 0, 0, 0, (),
369           "Return the current lilypond version as a list, e.g.
370 @code{(1 3 127 uu1)}. 
371 ")
372 {
373   char const* vs =  "\' (" MAJOR_VERSION " " MINOR_VERSION " "  PATCH_LEVEL " " MY_PATCH_LEVEL ")" ;
374   
375   return gh_eval_str ((char*)vs);
376 }
377
378 LY_DEFINE(ly_unit,  "ly-unit", 0, 0, 0, (),
379           "Return the unit used for lengths as a string.")
380 {
381   return scm_makfrom0str (INTERNAL_UNIT);
382 }
383
384 LY_DEFINE(ly_verbose,  "ly-verbose", 0, 0, 0, (),
385   "Return whether lilypond is being run in verbose mode.")
386 {
387   return gh_bool2scm (verbose_global_b);
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   for (char * p = s; *p; p++)
488     {
489       if (*p == '\n')
490         *p = ' ' ;
491     }
492   
493   if (!s[0] )
494     s = 0;
495
496
497   
498   while (s)
499     {
500       char *next = strchr (s, ' ');
501       if (next)
502         *next++ = 0;
503
504       create_list = gh_cons (ly_symbol2scm (s), create_list);
505       s = next;
506     }
507
508   free (orig);
509   return create_list;
510 }
511
512
513 SCM
514 ly_truncate_list (int k, SCM l )
515 {
516   if (k == 0)
517     {
518       l = SCM_EOL;
519     }
520   else
521     {
522       SCM s = l;
523       k--;
524       for (; gh_pair_p (s) && k--; s = ly_cdr (s))
525         ;
526
527       if (gh_pair_p (s))
528         {
529           gh_set_cdr_x (s, SCM_EOL);
530         }
531     }
532   return l;
533 }
534
535
536 String
537 print_scm_val (SCM val)
538 {
539   String realval = ly_scm2string (ly_write2scm (val));
540   if (realval.length () > 200)
541     realval = realval.left_string (100) + "\n :\n :\n" + realval.right_string (100);
542   
543   return realval;        
544 }
545
546 bool
547 type_check_assignment (SCM sym, SCM val,  SCM type_symbol) 
548 {
549   bool ok = true;
550
551   /*
552     Always succeeds.
553
554
555     TODO: should remove #f from allowed vals?
556    */
557   if (val == SCM_EOL || val == SCM_BOOL_F)
558     return ok;
559
560   
561   SCM type = SCM_EOL;
562
563   if (gh_symbol_p (sym))
564     type = scm_object_property (sym, type_symbol);
565
566   if (type != SCM_EOL && !gh_procedure_p (type))
567       {
568         warning (_f ("Can't find property type-check for `%s' (%s).",
569                      ly_symbol2string (sym).to_str0 (),
570                      ly_symbol2string (type_symbol).to_str0 ())
571                  + "  " + _ ("Perhaps you made a typing error?"));
572
573         /* Be strict when being anal :) */
574         if (internal_type_checking_global_b)
575           abort ();
576         
577         warning (_ ("Doing assignment anyway."));
578       }
579   else
580     {
581       if (val != SCM_EOL
582           && gh_procedure_p (type)
583           && gh_call1 (type, val) == SCM_BOOL_F)
584         {
585           SCM errport = scm_current_error_port ();
586           ok = false;
587           SCM typefunc = scm_primitive_eval (ly_symbol2scm ("type-name"));
588           SCM type_name = gh_call1 (typefunc, type);
589
590          
591           scm_puts (_f ("Type check for `%s' failed; value `%s' must be of type `%s'",
592                         ly_symbol2string (sym).to_str0 (),
593                         print_scm_val (val),
594                         ly_scm2string (type_name).to_str0 ()).to_str0 (),
595                     errport);
596           scm_puts ("\n", errport);                   
597         }
598     }
599   return ok;
600 }
601
602
603 /* some SCM abbrevs
604
605    zijn deze nou handig?
606    zijn ze er al in scheme, maar heten ze anders? */
607
608
609 /* Remove doubles from (sorted) list */
610 SCM
611 ly_unique (SCM list)
612 {
613   SCM unique = SCM_EOL;
614   for (SCM i = list; gh_pair_p (i); i = ly_cdr (i))
615     {
616       if (!gh_pair_p (ly_cdr (i))
617           || !gh_equal_p (ly_car (i), ly_cadr (i)))
618         unique = gh_cons (ly_car (i), unique);
619     }
620   return scm_reverse_x (unique, SCM_EOL);
621 }
622
623 /* tail add */
624 SCM
625 ly_snoc (SCM s, SCM list)
626 {
627   return gh_append2 (list, scm_list_n (s, SCM_UNDEFINED));
628 }
629
630
631 /* Split list at member s, removing s.
632    Return (BEFORE . AFTER) */
633 SCM
634 ly_split_list (SCM s, SCM list)
635 {
636   SCM before = SCM_EOL;
637   SCM after = list;
638   for (; gh_pair_p (after);)
639     {
640       SCM i = ly_car (after);
641       after = ly_cdr (after);
642       if (gh_equal_p (i, s))
643         break;
644       before = gh_cons (i, before);
645     }
646   return gh_cons ( scm_reverse_x (before, SCM_EOL),  after);
647   
648 }
649
650
651 void
652 taint (SCM *)
653 {
654   /*
655     nop.
656    */
657 }
658
659 /*
660   display stuff without using stack
661  */
662 SCM
663 display_list (SCM s)
664 {
665   SCM p = scm_current_output_port();
666
667   scm_puts ("(", p);
668   for (; gh_pair_p(s); s =gh_cdr(s))
669     {
670       scm_display (gh_car(s), p);
671       scm_puts (" ", p);      
672     }
673   scm_puts (")", p);
674   return SCM_UNSPECIFIED;
675 }
676
677 Slice
678 int_list_to_slice (SCM l)
679 {
680   Slice s;
681   s.set_empty ();
682   for (; gh_pair_p (l); l = gh_cdr (l))
683     {
684       if (gh_number_p (gh_car (l)))
685         s.add_point (gh_scm2int (gh_car (l))); 
686     }
687
688   return s;
689 }
690
691
692
693
694 /*
695   Return I-th element, or last elt L. If I < 0, then we take the first
696   element.
697
698   PRE: length (L) > 0
699  */
700 SCM
701 robust_list_ref(int i, SCM l)
702 {
703   while (i-- > 0 && gh_pair_p (gh_cdr(l)))
704     l = gh_cdr (l);
705
706   return gh_car(l);
707 }
708
709 static int module_count;
710
711 SCM
712 ly_make_anonymous_module ()
713 {
714   String s = "*anonymous-ly-" + to_string (module_count++) +  "*";
715   SCM mod = scm_c_resolve_module (s.to_str0());
716
717   scm_module_define (mod, ly_symbol2scm ("symbols-defined-here"), SCM_EOL);
718   return mod;
719 }
720
721 void
722 ly_copy_module_variable (SCM dest, SCM src)
723 {
724   SCM defd = ly_symbol2scm ("symbols-defined-here");
725   SCM dvar = scm_module_lookup (src, ly_symbol2scm ("symbols-defined-here"));
726   SCM lst =  scm_variable_ref (dvar);
727   for (SCM s =lst; gh_pair_p (s); s  = gh_cdr (s))
728     {
729       SCM var  = scm_module_lookup (src, gh_car (s));
730       scm_module_define (dest, gh_car (s),
731                          scm_variable_ref (var));
732     }
733
734   scm_module_define (dest, defd, lst);
735 }
736
737 SCM
738 ly_module_to_alist (SCM mod)
739 {
740   SCM defd = ly_symbol2scm ("symbols-defined-here");
741   SCM dvar = scm_module_lookup (mod, defd);
742   SCM lst = scm_variable_ref (dvar);
743
744   SCM alist =  SCM_EOL;
745   for (SCM s =lst; gh_pair_p (s); s  = gh_cdr (s))
746     {
747       SCM var  = scm_module_lookup (mod, gh_car (s));
748       alist= scm_cons (scm_cons (gh_car(s), scm_variable_ref (var)), alist);
749     }
750   return alist;
751 }