]> git.donarmstrong.com Git - lilypond.git/blob - lily/lily-guile.cc
``slikken kreng''
[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 /*
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.string ());
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.to_str0 ());
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)).to_str0 ());
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).to_str0 ());
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   char *p = SCM_STRING_CHARS(s);
216   String r (p);
217   return r;
218 }
219
220 SCM
221 index_get_cell (SCM s, Direction d)
222 {
223   assert (d);
224   return (d == LEFT) ? ly_car (s) : ly_cdr (s);
225 }
226
227 SCM
228 index_set_cell (SCM s, Direction d, SCM v)
229 {
230   if (d == LEFT)
231     gh_set_car_x (s, v);
232   else if (d == RIGHT)
233     gh_set_cdr_x (s, v);
234   return s;
235 }
236   
237 LY_DEFINE(ly_warning,"ly-warn", 1, 0, 0,
238   (SCM str),"Scheme callable function to issue the warning @code{msg}.
239 ")
240 {
241   assert (gh_string_p (str));
242   warning ("lily-guile: " + ly_scm2string (str));
243   return SCM_BOOL_T;
244 }
245
246 LY_DEFINE(ly_isdir,  "dir?", 1,0, 0,  (SCM s),
247           "type predicate. A direction is a -1, 0 or 1, where -1 represents left or
248 down and 1 represents right or up.
249 ")
250 {
251   if (gh_number_p (s))
252     {
253       int i = gh_scm2int (s);
254       return (i>= -1 && i <= 1)  ? SCM_BOOL_T : SCM_BOOL_F; 
255     }
256   return SCM_BOOL_F;
257 }
258
259 bool
260 ly_number_pair_p (SCM p)
261 {
262   return gh_pair_p (p) && gh_number_p (ly_car (p)) && gh_number_p (ly_cdr (p));
263 }
264
265 typedef void (*Void_fptr) ();
266 Array<Void_fptr> *scm_init_funcs_;
267
268 void add_scm_init_func (void (*f) ())
269 {
270   if (!scm_init_funcs_)
271     scm_init_funcs_ = new Array<Void_fptr>;
272
273   scm_init_funcs_->push (f);
274 }
275
276 extern void init_cxx_function_smobs ();
277
278
279 void
280 ly_init_guile ()
281 {
282   SCM last_mod = scm_current_module ();
283   scm_set_current_module (scm_c_resolve_module ("guile"));
284   
285   init_cxx_function_smobs ();
286   for (int i=scm_init_funcs_->size () ; i--;)
287     (scm_init_funcs_->elem (i)) ();
288
289   if (verbose_global_b)
290     progress_indication ("\n");
291   read_lily_scm_file ("lily.scm");
292
293   scm_set_current_module (last_mod);
294 }
295
296 unsigned int ly_scm_hash (SCM s)
297 {
298   return scm_ihashv (s, ~1u);
299 }
300
301
302
303 bool
304 ly_dir_p (SCM s)
305 {
306   if (gh_number_p (s))
307     {
308       int i = gh_scm2int (s);
309       return i>= -1 && i <= 1; 
310     }
311   return false;
312 }
313
314
315 bool
316 ly_axis_p (SCM s)
317 {
318   if (gh_number_p (s))
319     {
320       int i = gh_scm2int (s);
321       return i== 0 || i == 1;
322     }
323   return false;
324 }
325
326
327 Direction
328 to_dir (SCM s)
329 {
330   return (Direction) gh_scm2int (s);
331 }
332
333 Interval
334 ly_scm2interval (SCM p)
335 {
336   return  Interval (gh_scm2double (ly_car (p)),
337                     gh_scm2double (ly_cdr (p)));
338 }
339
340 SCM
341 ly_interval2scm (Drul_array<Real> i)
342 {
343   return gh_cons (gh_double2scm (i[LEFT]),
344                   gh_double2scm (i[RIGHT]));
345 }
346
347
348
349
350 bool
351 to_boolean (SCM s)
352 {
353   return gh_boolean_p (s) && gh_scm2bool (s);
354 }
355
356 /*
357   Appendable list L: the cdr contains the list, the car the last cons
358   in the list.
359  */
360 SCM
361 appendable_list ()
362 {
363   SCM s = gh_cons (SCM_EOL, SCM_EOL);
364   gh_set_car_x (s, s);
365   
366   return s;
367 }
368
369 void
370 appendable_list_append (SCM l, SCM elt)
371 {
372   SCM newcons = gh_cons (elt, SCM_EOL);
373   
374   gh_set_cdr_x (ly_car (l), newcons);      
375   gh_set_car_x (l, newcons);
376 }
377
378
379 SCM
380 ly_offset2scm (Offset o)
381 {
382   return gh_cons (gh_double2scm (o[X_AXIS]), gh_double2scm (o[Y_AXIS]));
383 }
384
385 Offset
386 ly_scm2offset (SCM s)
387 {
388   return Offset (gh_scm2double (ly_car (s)),
389                  gh_scm2double (ly_cdr (s)));
390 }
391
392 SCM
393 ly_type (SCM exp)
394 {
395   char const  * cp = "unknown";
396   if (gh_number_p (exp))
397     {
398       cp = "number";
399     }
400   else if (gh_string_p (exp))
401     {
402       cp = "string";
403     }
404   else if (gh_procedure_p (exp))
405     {
406       cp = "procedure";
407     }
408   else if (gh_boolean_p (exp))
409     {
410       cp = "boolean";
411     }
412   else if (gh_pair_p (exp))
413     {
414       cp = "list";
415     }
416
417   return ly_str02scm (cp);
418 }
419
420 /*
421   convert without too many decimals, and leave  a space at the end.
422  */
423    
424    
425 LY_DEFINE(ly_number2string,  "ly-number->string", 1, 0,0,
426           (SCM s),
427           " converts @var{num} to a string without generating many decimals. It
428 leaves a space at the end.
429 ")
430 {
431   assert (gh_number_p (s));
432
433   char str[400];                        // ugh.
434
435   if (scm_exact_p (s) == SCM_BOOL_F)
436     {
437       Real r (gh_scm2double (s));
438
439       if (isinf (r) || isnan (r))
440         {
441           programming_error ("Infinity or NaN encountered while converting Real number; setting to zero.");
442           r = 0.0;
443         }
444
445       sprintf (str, "%8.4f ", r);
446     }
447   else
448     {
449       sprintf (str, "%d ", gh_scm2int (s));
450     }
451
452   return ly_str02scm (str);
453 }
454
455 /*
456   Undef this to see if GUILE GC is causing too many swaps.
457  */
458
459 // #define TEST_GC
460
461 #ifdef TEST_GC
462 #include <libguile/gc.h>
463
464 static void *
465 greet_sweep (void *dummy1, void *dummy2, void *dummy3)
466 {
467    fprintf (stderr, "entering sweep\n");
468 }
469
470 static void *
471 wave_sweep_goodbye (void *dummy1, void *dummy2, void *dummy3)
472 {
473    fprintf (stderr, "leaving sweep\n");
474 }
475 #endif
476
477
478 #include "version.hh"
479 LY_DEFINE(ly_version,  "ly-version", 0, 0, 0, (),
480           "Return the current lilypond version as a list, e.g.
481 @code{(1 3 127 uu1)}. 
482 ")
483 {
484   char const* vs =  "\' (" MAJOR_VERSION " " MINOR_VERSION " "  PATCH_LEVEL " " MY_PATCH_LEVEL ")" ;
485   
486   return gh_eval_str ((char*)vs);
487 }
488
489 LY_DEFINE(ly_unit,  "ly-unit", 0, 0, 0, (),
490           "Return the unit used for lengths as a string.")
491 {
492   return ly_str02scm (INTERNAL_UNIT);
493 }
494
495 LY_DEFINE(ly_verbose,  "ly-verbose", 0, 0, 0, (),
496   "Return whether lilypond is being run in verbose mode.")
497 {
498   return gh_bool2scm (verbose_global_b);
499 }
500
501 static void
502 init_functions ()
503 {
504 #ifdef TEST_GC 
505   scm_c_hook_add (&scm_before_mark_c_hook, greet_sweep, 0, 0);
506   scm_c_hook_add (&scm_before_sweep_c_hook, wave_sweep_goodbye, 0, 0);
507 #endif
508 }
509
510 ADD_SCM_INIT_FUNC (funcs, init_functions);
511
512 SCM
513 ly_deep_copy (SCM src)
514 {
515   if (gh_pair_p (src))
516     {
517       return gh_cons (ly_deep_copy (ly_car (src)), ly_deep_copy (ly_cdr (src)));
518     }
519   else if (gh_vector_p (src))
520     {
521       int  l = SCM_VECTOR_LENGTH (src);
522       SCM nv = scm_c_make_vector (l, SCM_UNDEFINED);
523       for (int i  =0 ; i< l ; i++)
524         {
525           SCM si = gh_int2scm (i);
526           scm_vector_set_x (nv, si, ly_deep_copy (scm_vector_ref (src, si))); 
527         }
528     }
529   else
530     return src;
531
532   return src;
533 }
534
535
536
537
538 SCM
539 ly_assoc_chain (SCM key, SCM achain)
540 {
541   if (gh_pair_p (achain))
542     {
543       SCM handle = scm_assoc (key, ly_car (achain));
544       if (gh_pair_p (handle))
545         return handle;
546       else
547         return ly_assoc_chain (key, ly_cdr (achain));
548     }
549   else
550     return SCM_BOOL_F;
551 }
552
553 /* looks the key up in the cdrs of the alist-keys
554    - ignoring the car and ignoring non-pair keys.
555    Returns first match found, i.e.
556
557    alist = ((1 . 10)
558                    ((1 . 2) . 11)
559                    ((2 . 1) . 12)
560                    ((3 . 0) . 13)
561                    ((4 . 1) . 14) )
562
563 I would like (ly_assoc_cdr 1) to return 12 - because it's the first
564 element with the cdr of the key = 1.  In other words (alloc_cdr key)
565 corresponds to call
566
567 (alloc (anything . key))
568
569
570
571 */
572 SCM
573 ly_assoc_cdr (SCM key, SCM alist)
574 {
575   if (gh_pair_p (alist)) {
576     SCM trykey = ly_caar(alist);
577     if(gh_pair_p(trykey) && to_boolean(scm_equal_p(key,ly_cdr(trykey))))
578       return ly_car(alist);
579     else
580       return ly_assoc_cdr (key, ly_cdr (alist));
581   }
582   else
583     return SCM_BOOL_F;
584 }
585
586 /*
587   LIST has the form "sym1 sym2 sym3\nsym4\nsym5"
588
589   i.e. \n and ' ' can be used interchangeably as separators.
590  */
591 SCM
592 parse_symbol_list (const char * list)
593 {
594   char * s = strdup (list);
595   char *orig = s;
596   SCM create_list = SCM_EOL;
597
598   for (char * p = s; *p; p++)
599     {
600       if (*p == '\n')
601         *p = ' ' ;
602     }
603   
604   if (!s[0] )
605     s = 0;
606
607
608   
609   while (s)
610     {
611       char *next = strchr (s, ' ');
612       if (next)
613         *next++ = 0;
614
615       create_list = gh_cons (ly_symbol2scm (s), create_list);
616       s = next;
617     }
618
619   free (orig);
620   return create_list;
621 }
622
623
624 SCM
625 ly_truncate_list (int k, SCM l )
626 {
627   if (k == 0)
628     {
629       l = SCM_EOL;
630     }
631   else
632     {
633       SCM s = l;
634       k--;
635       for (; gh_pair_p (s) && k--; s = ly_cdr (s))
636         ;
637
638       if (gh_pair_p (s))
639         {
640           gh_set_cdr_x (s, SCM_EOL);
641         }
642     }
643   return l;
644 }
645
646 SCM my_gh_symbol2scm (const char* x)
647 {
648   return gh_symbol2scm ((char*)x);
649 }
650
651 String
652 print_scm_val (SCM val)
653 {
654   String realval = ly_scm2string (ly_write2scm (val));
655   if (realval.length () > 200)
656     realval = realval.left_string (100) + "\n :\n :\n" + realval.right_string (100);
657   
658   return realval;        
659 }
660
661 bool
662 type_check_assignment (SCM sym, SCM val,  SCM type_symbol) 
663 {
664   bool ok = true;
665
666   /*
667     Always succeeds.
668
669
670     TODO: should remove #f from allowed vals?
671    */
672   if (val == SCM_EOL || val == SCM_BOOL_F)
673     return ok;
674
675   
676   SCM type = SCM_EOL;
677
678   if (gh_symbol_p (sym))
679     type = scm_object_property (sym, type_symbol);
680
681   if (type != SCM_EOL && !gh_procedure_p (type))
682       {
683         warning (_f ("Can't find property type-check for `%s' (%s).  Perhaps you made a typing error? Doing assignment anyway.",
684                      ly_symbol2string (sym).to_str0 (),
685                      ly_symbol2string (type_symbol).to_str0 ()
686
687                      ));
688       }
689   else
690     {
691       if (val != SCM_EOL
692           && gh_procedure_p (type)
693           && gh_call1 (type, val) == SCM_BOOL_F)
694         {
695           SCM errport = scm_current_error_port ();
696           ok = false;
697           SCM typefunc = scm_primitive_eval (ly_symbol2scm ("type-name"));
698           SCM type_name = gh_call1 (typefunc, type);
699
700          
701           scm_puts (_f ("Type check for `%s' failed; value `%s' must be of type `%s'",
702                         ly_symbol2string (sym).to_str0 (),
703                         print_scm_val (val),
704                         ly_scm2string (type_name).to_str0 ()).to_str0 (),
705                     errport);
706           scm_puts ("\n", errport);                   
707         }
708     }
709   return ok;
710 }
711
712
713 /* some SCM abbrevs
714
715    zijn deze nou handig?
716    zijn ze er al in scheme, maar heten ze anders? */
717
718
719 /* Remove doubles from (sorted) list */
720 SCM
721 ly_unique (SCM list)
722 {
723   SCM unique = SCM_EOL;
724   for (SCM i = list; gh_pair_p (i); i = ly_cdr (i))
725     {
726       if (!gh_pair_p (ly_cdr (i))
727           || !gh_equal_p (ly_car (i), ly_cadr (i)))
728         unique = gh_cons (ly_car (i), unique);
729     }
730   return scm_reverse_x (unique, SCM_EOL);
731 }
732
733 /* tail add */
734 SCM
735 ly_snoc (SCM s, SCM list)
736 {
737   return gh_append2 (list, scm_list_n (s, SCM_UNDEFINED));
738 }
739
740
741 /* Split list at member s, removing s.
742    Return (BEFORE . AFTER) */
743 SCM
744 ly_split_list (SCM s, SCM list)
745 {
746   SCM before = SCM_EOL;
747   SCM after = list;
748   for (; gh_pair_p (after);)
749     {
750       SCM i = ly_car (after);
751       after = ly_cdr (after);
752       if (gh_equal_p (i, s))
753         break;
754       before = gh_cons (i, before);
755     }
756   return gh_cons ( scm_reverse_x (before, SCM_EOL),  after);
757   
758 }
759
760
761 void
762 taint (SCM *)
763 {
764   /*
765     nop.
766    */
767 }
768
769 /*
770   display stuff without using stack
771  */
772 SCM
773 display_list (SCM s)
774 {
775   SCM p = scm_current_output_port();
776
777   scm_puts ("(", p);
778   for (; gh_pair_p(s); s =gh_cdr(s))
779     {
780       scm_display (gh_car(s), p);
781       scm_puts (" ", p);      
782     }
783   scm_puts (")", p);
784   return SCM_UNSPECIFIED;
785 }
786
787 Slice
788 int_list_to_slice (SCM l)
789 {
790   Slice s;
791   s.set_empty ();
792   for (; gh_pair_p (l); l = gh_cdr (l))
793     {
794       if (gh_number_p (gh_car (l)))
795         s.add_point (gh_scm2int (gh_car (l))); 
796     }
797
798   return s;
799 }
800
801
802
803
804 /*
805   Return I-th element, or last elt L. If I < 0, then we take the first
806   element.
807
808   PRE: length (L) > 0
809  */
810 SCM
811 robust_list_ref(int i, SCM l)
812 {
813   while (i-- > 0 && gh_pair_p (gh_cdr(l)))
814     l = gh_cdr (l);
815
816   return gh_car(l);
817 }