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