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