]> git.donarmstrong.com Git - lilypond.git/blob - lily/lily-guile.cc
* lily/lily-guile.cc (type_check_assignment): use
[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--2004 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 <ctype.h>
17
18 #include "lily-proto.hh"
19
20 /* macosx fix:
21
22
23  source-file.hh includes cmath which undefines isinf and isnan
24 */
25 inline int my_isinf (Real r) { return isinf (r); }
26 inline int my_isnan (Real r) { return isnan (r); }
27
28
29
30 #include "libc-extension.hh"
31 #include "lily-guile.hh"
32 #include "main.hh"
33 #include "file-path.hh"
34 #include "warn.hh"
35 #include "direction.hh"
36 #include "offset.hh"
37 #include "interval.hh"
38 #include "pitch.hh"
39 #include "dimensions.hh"
40 #include "source-file.hh"
41
42 // #define TEST_GC
43
44 SCM
45 ly_last (SCM list)
46 {
47   return ly_car (scm_last_pair (list));
48 }
49
50
51 SCM
52 ly_write2scm (SCM s)
53 {
54   SCM port = scm_mkstrport (SCM_INUM0, 
55                             scm_make_string (SCM_INUM0, SCM_UNDEFINED),
56                             SCM_OPN | SCM_WRTNG,
57                             "ly_write2string");
58   //  SCM write = scm_eval_3 (ly_symbol2scm ("write"), s, SCM_EOL);
59   SCM write = scm_primitive_eval (ly_symbol2scm ("write"));
60   
61   // scm_apply (write, port, SCM_EOL);
62   gh_call2 (write, s, port);
63   return scm_strport_to_string (port);
64 }
65
66
67 SCM
68 ly_quote_scm (SCM s)
69 {
70   return scm_list_n (ly_symbol2scm ("quote"), s, SCM_UNDEFINED);
71 }
72
73 String
74 ly_symbol2string (SCM s)
75 {
76   assert (gh_symbol_p (s));
77   return String ((Byte*)SCM_STRING_CHARS (s), (int) SCM_STRING_LENGTH (s));
78 }
79
80 String
81 gulp_file_to_string (String fn)
82 {
83   String s = global_path.find (fn);
84   if (s == "")
85     {
86       String e = _f ("can't find file: `%s'", fn);
87       e += " ";
88       e += _f ("(load path: `%s')", global_path.to_string ());
89       error (e);
90     }
91   else if (verbose_global_b)
92     progress_indication ("[" + s);
93
94   int n;
95   char * str = gulp_file (s, &n);
96   String result (str);
97   delete[] str;
98   
99   if (verbose_global_b)
100     progress_indication ("]");
101
102   return result;
103 }
104
105 LY_DEFINE (ly_gulp_file, "ly:gulp-file",
106            1, 0, 0, (SCM name),
107           "Read the file @var{name}, and return its contents in a string.  "
108            "The file is looked up using the search path.")
109 {
110   return scm_makfrom0str (gulp_file_to_string (ly_scm2string (name)).to_str0 ());
111 }
112
113
114 extern "C" {
115   // maybe gdb 5.0 becomes quicker if it doesn't do fancy C++ typing?
116 void
117 ly_display_scm (SCM s)
118 {
119   gh_display (s);
120   gh_newline ();
121 }
122 };
123
124 String
125 ly_scm2string (SCM s)
126 {
127   assert (gh_string_p (s));
128
129   char *p = SCM_STRING_CHARS (s);
130   String r (p);
131   return r;
132 }
133
134 SCM
135 index_get_cell (SCM s, Direction d)
136 {
137   
138   assert (d);
139   return (d == LEFT) ? ly_car (s) : ly_cdr (s);
140 }
141
142 SCM
143 index_set_cell (SCM s, Direction d, SCM v)
144 {
145   if (d == LEFT)
146     gh_set_car_x (s, v);
147   else if (d == RIGHT)
148     gh_set_cdr_x (s, v);
149   return s;
150 }
151   
152 LY_DEFINE (ly_warning,"ly:warn", 1, 0, 0,
153   (SCM str), "Scheme callable function to issue the warning @code{msg}.")
154 {
155   SCM_ASSERT_TYPE (gh_string_p (str), str, SCM_ARG1, __FUNCTION__, "string");
156   progress_indication ("\n");
157   warning ("lily-guile: " + ly_scm2string (str));
158   return SCM_BOOL_T;
159 }
160
161 LY_DEFINE (ly_dir_p,  "ly:dir?", 1,0, 0,  (SCM s),
162           "type predicate. A direction is @code{-1}, @code{0} or "
163            "@code{1}, where @code{-1} represents "
164           "left or down and @code{1} represents right or up.")
165 {
166   if (gh_number_p (s))
167     {
168       int i = gh_scm2int (s);
169       return (i>= -1 && i <= 1)  ? SCM_BOOL_T : SCM_BOOL_F; 
170     }
171   return SCM_BOOL_F;
172 }
173
174 bool
175 is_number_pair (SCM p)
176 {
177   return gh_pair_p (p) && gh_number_p (ly_car (p)) && gh_number_p (ly_cdr (p));
178 }
179
180 typedef void (*Void_fptr) ();
181 Array<Void_fptr> *scm_init_funcs_;
182
183 void add_scm_init_func (void (*f) ())
184 {
185   if (!scm_init_funcs_)
186     scm_init_funcs_ = new Array<Void_fptr>;
187
188   scm_init_funcs_->push (f);
189 }
190
191
192 void
193 ly_init_ly_module (void *)
194 {
195   for (int i=scm_init_funcs_->size () ; i--;)
196     (scm_init_funcs_->elem (i)) ();
197
198   if (verbose_global_b)
199     progress_indication ("\n");
200   
201   scm_primitive_load_path (scm_makfrom0str ("lily.scm"));
202 }
203
204
205 SCM global_lily_module;
206
207 void
208 ly_init_guile ()
209 {
210   global_lily_module = scm_c_define_module ("lily", ly_init_ly_module, 0);
211   scm_c_use_module ("lily");
212 }
213
214 unsigned int ly_scm_hash (SCM s)
215 {
216   return scm_ihashv (s, ~1u);
217 }
218
219
220
221 bool
222 is_direction (SCM s)
223 {
224   if (gh_number_p (s))
225     {
226       int i = gh_scm2int (s);
227       return i>= -1 && i <= 1; 
228     }
229   return false;
230 }
231
232
233 bool
234 is_axis (SCM s)
235 {
236   if (gh_number_p (s))
237     {
238       int i = gh_scm2int (s);
239       return i== 0 || i == 1;
240     }
241   return false;
242 }
243
244
245 Direction
246 to_dir (SCM s)
247 {
248   return SCM_INUMP (s) ?  (Direction) gh_scm2int (s) : CENTER;
249 }
250
251 Interval
252 ly_scm2interval (SCM p)
253 {
254   return  Interval (gh_scm2double (ly_car (p)),
255                     gh_scm2double (ly_cdr (p)));
256 }
257
258 Drul_array<Real>
259 ly_scm2realdrul (SCM p)
260 {
261   return  Drul_array<Real> (gh_scm2double (ly_car (p)),
262                             gh_scm2double (ly_cdr (p)));
263 }
264
265 SCM
266 ly_interval2scm (Drul_array<Real> i)
267 {
268   return gh_cons (gh_double2scm (i[LEFT]),
269                   gh_double2scm (i[RIGHT]));
270 }
271
272
273
274
275 bool
276 to_boolean (SCM s)
277 {
278   return gh_boolean_p (s) && gh_scm2bool (s);
279 }
280
281 /*
282   Appendable list L: the cdr contains the list, the car the last cons
283   in the list.
284  */
285 SCM
286 appendable_list ()
287 {
288   SCM s = gh_cons (SCM_EOL, SCM_EOL);
289   gh_set_car_x (s, s);
290   
291   return s;
292 }
293
294 void
295 appendable_list_append (SCM l, SCM elt)
296 {
297   SCM newcons = gh_cons (elt, SCM_EOL);
298   
299   gh_set_cdr_x (ly_car (l), newcons);      
300   gh_set_car_x (l, newcons);
301 }
302
303
304 SCM
305 ly_offset2scm (Offset o)
306 {
307   return gh_cons (gh_double2scm (o[X_AXIS]), gh_double2scm (o[Y_AXIS]));
308 }
309
310 Offset
311 ly_scm2offset (SCM s)
312 {
313   return Offset (gh_scm2double (ly_car (s)),
314                  gh_scm2double (ly_cdr (s)));
315 }
316
317    
318 LY_DEFINE (ly_number2string, "ly:number->string",
319            1, 0, 0, (SCM s),
320            "Convert @var{num} to a string without generating many decimals.")
321 {
322   SCM_ASSERT_TYPE (gh_number_p (s), s, SCM_ARG1, __FUNCTION__, "number");
323
324   char str[400];                        // ugh.
325
326   if (scm_exact_p (s) == SCM_BOOL_F)
327     {
328       Real r (gh_scm2double (s));
329
330       if (my_isinf (r) || my_isnan (r))
331         {
332           programming_error ("Infinity or NaN encountered while converting Real number; setting to zero.");
333           r = 0.0;
334         }
335
336       sprintf (str, "%08.4f", r);
337     }
338   else
339     sprintf (str, "%d", gh_scm2int (s));
340
341   return scm_makfrom0str (str);
342 }
343
344 /*
345   Undef this to see if GUILE GC is causing too many swaps.
346  */
347
348 //#define TEST_GC
349
350 #ifdef TEST_GC
351 #include <libguile/gc.h>
352
353 static void *
354 greet_sweep (void *dummy1, void *dummy2, void *dummy3)
355 {
356    fprintf (stderr, "entering sweep\n");
357 }
358
359 static void *
360 wave_sweep_goodbye (void *dummy1, void *dummy2, void *dummy3)
361 {
362    fprintf (stderr, "leaving sweep\n");
363 }
364 #endif
365
366
367 #include "version.hh"
368 LY_DEFINE (ly_version,  "ly:version", 0, 0, 0, (),
369           "Return the current lilypond version as a list, e.g. @code{(1 3 127 uu1)}. ")
370 {
371   char const* vs =  "\'(" MAJOR_VERSION " " MINOR_VERSION " "  PATCH_LEVEL " " MY_PATCH_LEVEL ")" ;
372   
373   return gh_eval_str ((char*)vs);
374 }
375
376 LY_DEFINE (ly_unit,  "ly:unit", 0, 0, 0, (),
377           "Return the unit used for lengths as a string.")
378 {
379   return scm_makfrom0str (INTERNAL_UNIT);
380 }
381
382
383
384 LY_DEFINE (ly_dimension_p,  "ly:dimension?", 1, 0, 0, (SCM d),
385           "Return @var{d} is a number. Used to distinguish length "
386           "variables from normal numbers.")
387 {
388   return scm_number_p (d);
389 }
390
391 static void
392 init_functions ()
393 {
394 #ifdef TEST_GC 
395   scm_c_hook_add (&scm_before_mark_c_hook, greet_sweep, 0, 0);
396   scm_c_hook_add (&scm_before_sweep_c_hook, wave_sweep_goodbye, 0, 0);
397 #endif
398 }
399
400 ADD_SCM_INIT_FUNC (funcs, init_functions);
401
402 SCM
403 ly_deep_copy (SCM src)
404 {
405   if (gh_pair_p (src))
406     {
407       return gh_cons (ly_deep_copy (ly_car (src)), ly_deep_copy (ly_cdr (src)));
408     }
409   else if (gh_vector_p (src))
410     {
411       int  l = SCM_VECTOR_LENGTH (src);
412       SCM nv = scm_c_make_vector (l, SCM_UNDEFINED);
413       for (int i  =0 ; i< l ; i++)
414         {
415           SCM si = gh_int2scm (i);
416           scm_vector_set_x (nv, si, ly_deep_copy (scm_vector_ref (src, si))); 
417         }
418     }
419   else
420     return src;
421
422   return src;
423 }
424
425
426
427
428 SCM
429 ly_assoc_chain (SCM key, SCM achain)
430 {
431   if (gh_pair_p (achain))
432     {
433       SCM handle = scm_assoc (key, ly_car (achain));
434       if (gh_pair_p (handle))
435         return handle;
436       else
437         return ly_assoc_chain (key, ly_cdr (achain));
438     }
439   else
440     return SCM_BOOL_F;
441 }
442
443 /* looks the key up in the cdrs of the alist-keys
444    - ignoring the car and ignoring non-pair keys.
445    Returns first match found, i.e.
446
447    alist = ((1 . 10)
448                    ((1 . 2) . 11)
449                    ((2 . 1) . 12)
450                    ((3 . 0) . 13)
451                    ((4 . 1) . 14) )
452
453 I would like (ly_assoc_cdr 1) to return 12 - because it's the first
454 element with the cdr of the key = 1.  In other words (alloc_cdr key)
455 corresponds to call
456
457 (alloc (anything . key))
458
459
460
461 */
462 SCM
463 ly_assoc_cdr (SCM key, SCM alist)
464 {
465   if (gh_pair_p (alist)) {
466     SCM trykey = ly_caar (alist);
467     if (gh_pair_p (trykey) && to_boolean (scm_equal_p (key,ly_cdr (trykey))))
468       return ly_car (alist);
469     else
470       return ly_assoc_cdr (key, ly_cdr (alist));
471   }
472   else
473     return SCM_BOOL_F;
474 }
475
476 /*
477   LIST has the form "sym1 sym2 sym3\nsym4\nsym5"
478
479   i.e. \n and ' ' can be used interchangeably as separators.
480  */
481 SCM
482 parse_symbol_list (const char * list)
483 {
484   char * s = strdup (list);
485   char *orig = s;
486   SCM create_list = SCM_EOL;
487
488   char * e = s + strlen (s) - 1;
489   while (e >= s && isspace (*e))
490     *e -- = 0;
491
492   for (char * p = s; *p; p++)
493     {
494       if (*p == '\n')
495         *p = ' ' ;
496     }
497   
498   if (!s[0] )
499     s = 0;
500
501
502   
503   while (s)
504     {
505       char *next = strchr (s, ' ');
506       if (next)
507         *next++ = 0;
508
509       create_list = gh_cons (ly_symbol2scm (s), create_list);
510       s = next;
511     }
512
513   free (orig);
514   return create_list;
515 }
516
517
518 SCM
519 ly_truncate_list (int k, SCM l )
520 {
521   if (k == 0)
522     {
523       l = SCM_EOL;
524     }
525   else
526     {
527       SCM s = l;
528       k--;
529       for (; gh_pair_p (s) && k--; s = ly_cdr (s))
530         ;
531
532       if (gh_pair_p (s))
533         {
534           gh_set_cdr_x (s, SCM_EOL);
535         }
536     }
537   return l;
538 }
539
540
541 String
542 print_scm_val (SCM val)
543 {
544   String realval = ly_scm2string (ly_write2scm (val));
545   if (realval.length () > 200)
546     realval = realval.left_string (100) + "\n :\n :\n" + realval.right_string (100);
547   
548   return realval;        
549 }
550
551 bool
552 type_check_assignment (SCM sym, SCM val,  SCM type_symbol) 
553 {
554   bool ok = true;
555
556   /*
557     Always succeeds.
558
559
560     TODO: should remove #f from allowed vals?
561    */
562   if (val == SCM_EOL || val == SCM_BOOL_F)
563     return ok;
564
565   if (!gh_symbol_p (sym))
566 #if 0
567     return false;
568 #else
569   /*
570     This is used for autoBeamSettings.
571
572     TODO: deprecate the use of \override and \revert for
573     autoBeamSettings?
574
575     or use a symbol autoBeamSettingS?  
576    */
577   return true; 
578 #endif
579   
580   SCM type = scm_object_property (sym, type_symbol);
581
582   if (type != SCM_EOL && !gh_procedure_p (type))
583       {
584         warning (_f ("Can't find property type-check for `%s' (%s).",
585                      ly_symbol2string (sym).to_str0 (),
586                      ly_symbol2string (type_symbol).to_str0 ())
587                  + "  " + _ ("Perhaps you made a typing error?"));
588
589         /* Be strict when being anal :) */
590         if (internal_type_checking_global_b)
591           abort ();
592         
593         warning (_ ("Doing assignment anyway."));
594       }
595   else
596     {
597       if (val != SCM_EOL
598           && gh_procedure_p (type)
599           && gh_call1 (type, val) == SCM_BOOL_F)
600         {
601           SCM errport = scm_current_error_port ();
602           ok = false;
603           SCM typefunc = ly_scheme_function ("type-name");
604           SCM type_name = gh_call1 (typefunc, type);
605
606          
607           scm_puts (_f ("Type check for `%s' failed; value `%s' must be of type `%s'",
608                         ly_symbol2string (sym).to_str0 (),
609                         print_scm_val (val),
610                         ly_scm2string (type_name).to_str0 ()).to_str0 (),
611                     errport);
612           scm_puts ("\n", errport);                   
613         }
614     }
615   return ok;
616 }
617
618
619 /* some SCM abbrevs
620
621    zijn deze nou handig?
622    zijn ze er al in scheme, maar heten ze anders? */
623
624
625 /* Remove doubles from (sorted) list */
626 SCM
627 ly_unique (SCM list)
628 {
629   SCM unique = SCM_EOL;
630   for (SCM i = list; gh_pair_p (i); i = ly_cdr (i))
631     {
632       if (!gh_pair_p (ly_cdr (i))
633           || !gh_equal_p (ly_car (i), ly_cadr (i)))
634         unique = gh_cons (ly_car (i), unique);
635     }
636   return scm_reverse_x (unique, SCM_EOL);
637 }
638
639 /* tail add */
640 SCM
641 ly_snoc (SCM s, SCM list)
642 {
643   return gh_append2 (list, scm_list_n (s, SCM_UNDEFINED));
644 }
645
646
647 /* Split list at member s, removing s.
648    Return (BEFORE . AFTER) */
649 SCM
650 ly_split_list (SCM s, SCM list)
651 {
652   SCM before = SCM_EOL;
653   SCM after = list;
654   for (; gh_pair_p (after);)
655     {
656       SCM i = ly_car (after);
657       after = ly_cdr (after);
658       if (gh_equal_p (i, s))
659         break;
660       before = gh_cons (i, before);
661     }
662   return gh_cons ( scm_reverse_x (before, SCM_EOL),  after);
663   
664 }
665
666
667 void
668 taint (SCM *)
669 {
670   /*
671     nop.
672    */
673 }
674
675 /*
676   display stuff without using stack
677  */
678 SCM
679 display_list (SCM s)
680 {
681   SCM p = scm_current_output_port ();
682
683   scm_puts ("(", p);
684   for (; gh_pair_p (s); s =gh_cdr (s))
685     {
686       scm_display (gh_car (s), p);
687       scm_puts (" ", p);      
688     }
689   scm_puts (")", p);
690   return SCM_UNSPECIFIED;
691 }
692
693 Slice
694 int_list_to_slice (SCM l)
695 {
696   Slice s;
697   s.set_empty ();
698   for (; gh_pair_p (l); l = gh_cdr (l))
699     {
700       if (gh_number_p (gh_car (l)))
701         s.add_point (gh_scm2int (gh_car (l))); 
702     }
703
704   return s;
705 }
706
707
708 /*
709   Return I-th element, or last elt L. If I < 0, then we take the first
710   element.
711
712   PRE: length (L) > 0
713  */
714 SCM
715 robust_list_ref (int i, SCM l)
716 {
717   while (i-- > 0 && gh_pair_p (gh_cdr (l)))
718     l = gh_cdr (l);
719
720   return gh_car (l);
721 }
722
723
724
725 Real
726 robust_scm2double (SCM k, double x)
727 {
728   if (gh_number_p (k))
729     x = gh_scm2double (k);
730   return x;
731 }
732
733 Interval
734 robust_scm2interval (SCM k, Drul_array<Real> v)
735 {
736   Interval i;
737   i[LEFT]= v[LEFT];
738   i[RIGHT]= v[RIGHT];
739   if (is_number_pair (k))
740     i = ly_scm2interval (k);
741   return i;
742 }
743
744 Drul_array<Real>
745 robust_scm2drul (SCM k, Drul_array<Real> v)
746 {
747   if (is_number_pair (k))
748     v = ly_scm2interval (k);
749   return v;
750 }
751
752 Offset
753 robust_scm2offset (SCM k, Offset o)
754 {
755   if (is_number_pair (k))
756     o = ly_scm2offset (k);
757
758   return o;
759 }
760
761
762 int
763 robust_scm2int (SCM k, int o)
764 {
765   if (scm_integer_p (k) == SCM_BOOL_T)
766     o = gh_scm2int (k);
767
768   return o;
769 }
770
771
772 SCM
773 alist_to_hashq (SCM alist)
774 {
775   int i = scm_ilength (alist);
776   if (i < 0)
777     return scm_make_vector (gh_int2scm (0), SCM_EOL);
778           
779   SCM tab = scm_make_vector (gh_int2scm (i), SCM_EOL);
780   for (SCM s = alist; gh_pair_p (s); s = ly_cdr (s))
781     {
782       SCM pt = ly_cdar (s);
783       scm_hashq_set_x (tab, ly_caar (s), pt);
784     }
785   return tab; 
786 }
787
788 #if 1
789 /*
790   Debugging mem leaks:
791  */
792 LY_DEFINE (ly_protects, "ly:protects", 0, 0, 0, (),
793           "Return hash of protected objects.")
794 {
795   return scm_protects;
796 }
797 #endif