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