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