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