]> git.donarmstrong.com Git - lilypond.git/blob - lily/include/smobs.hh
Issue 4373: Start up GUILE type system before anything else
[lilypond.git] / lily / include / smobs.hh
1 /*
2   This file is part of LilyPond, the GNU music typesetter.
3
4   Copyright (C) 1999--2015 Han-Wen Nienhuys <hanwen@xs4all.nl>
5
6   LilyPond is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   LilyPond is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #ifndef SMOBS_HH
21 #define SMOBS_HH
22
23 #include "lily-guile.hh"
24 #include "warn.hh"
25 #include <string>
26
27 /*
28   Smobs are GUILEs mechanism of exporting C(++) objects to the Scheme
29   world.  They are documented in the GUILE manual.
30
31
32   In LilyPond, C++ objects can be placed under the control of GUILE's
33   type system and garbage collection mechanism by inheriting from one
34   of several Smob base classes.
35
36   There are two types of smob objects.
37
38   1. Simple smobs are intended for simple objects like numbers:
39   immutable objects that can be copied without change of meaning.
40
41   To obtain an SCM version of a simple smob, use the member function
42   SCM smobbed_copy ().
43
44   Simple smobs are created by deriving from Simple_smob<Classname>.
45
46   A simple smob is only optionally under the reign of the GUILE
47   garbage collector: its usual life time is that of a normal C++
48   object.  While a smobbed_copy () is fully under control of the
49   garbage collector and will have its mark_smob function called during
50   garbage collection, an automatic variable of this type will not have
51   mark_smob called, but rather have its memory image in the call stack
52   scanned for contained non-immediate SCM values.  Anything requiring
53   more complex mark_smob behavior is not suitable for a simple smob.
54
55   When you create a smobbed_copy, the _copy_ is fully managed by the
56   GUILE memory system.  As a corollary, multiple smobbed_copy calls
57   yield multiple GUILE objects generally not eq? to each other.
58
59   2. Complex smobs are objects that have an identity. These objects
60   carry this identity in the form of a self_scm () method, which is a
61   SCM pointer to the object itself.  Complex smobs are always under
62   control of the GUILE memory system.
63
64   The constructor for a complex smob should have 3 steps:
65
66   * initialize all SCM members to an immediate value (like SCM_EOL)
67
68   * call smobify_self ()
69
70   * initialize SCM members
71
72   For example,
73
74   Complex_smob::Complex_smob : public Smob<Complex_smob> () {
75   scm_member_ = SCM_EOL;
76   smobify_self ();
77   scm_member_ = <..what you want to store..>
78   }
79
80   after construction, the self_scm () field of a complex smob is
81   protected from Garbage Collection.  This protection should be
82   removed once the object is put into another (reachable) Scheme data
83   structure, i.e.
84
85   Complex_smob *p = new Complex_smob;
86   list = scm_cons (p->self_scm (), list);
87   p->unprotect ();
88
89   Since unprotect returns the SCM object itself, this particular case
90   can be written as
91
92   Complex_smob *p = new Complex_smob;
93   list = scm_cons (p->unprotect (), list);
94
95   Complex smobs are created by deriving from Smob<Classname>.
96
97   CALLING INTERFACE
98
99   Common public methods to C++ smob objects:
100
101   - unsmob (SCM x) - unpacks X and returns pointer to the C++ object,
102     or 0 if it has the wrong type.  This can be used as a boolean
103     condition at C++ level.
104   - smob_p (SCM x) returns #t or #f at Scheme level.
105
106   IMPLEMENTATION
107
108   For implementating a class, the following public members can be
109   provided in the top class itself:
110
111   - SCM equal_p (SCM a, SCM b) - compare A and B. Returns a Scheme
112     boolean.  If the class does not define this function, equal? will
113     be equivalent to eq?.  The function will only be called when both
114     objects are of the respective type and not eq? to each other.
115
116   - mark_smob () function, that calls scm_gc_mark () on all Scheme
117     objects in the class.  If the class does not define this function,
118     it must not contain non-immediate Scheme values.
119
120   - a print_smob () function, that displays a representation for
121     debugging purposes.  If the class does not define this function,
122     the output will be #<Classname> when printing.
123
124   - a static const type_p_name_[] string set to something like
125     "ly:grob?".  When provided, an accordingly named function for
126     checking for the given smob type will be available in Scheme.
127
128 */
129
130 // Initialization class.  Create a variable or static data member of
131 // this type at global scope (or creation will happen too late for
132 // Scheme initialization), initialising with a function to be called.
133 // Reference somewhere (like in the constructor of the containing
134 // class) to make sure the variable is actually instantiated.
135
136 class Scm_init {
137   static const Scm_init * list_;
138   void (*const fun_)(void);
139   Scm_init const * const next_;
140   Scm_init ();          // don't use default constructor, don't define
141   Scm_init (const Scm_init &);  // don't define copy constructor
142 public:
143   Scm_init (void (*fun) (void)) : fun_ (fun), next_ (list_)
144   { list_ = this; }
145   static void init ();
146 };
147
148 template <class Super>
149 class Smob_base
150 {
151   static scm_t_bits smob_tag_;
152   static Scm_init scm_init_;
153   static void init (void);
154   static string smob_name_;
155   static Super *unchecked_unsmob (SCM s)
156   {
157     return reinterpret_cast<Super *> (SCM_SMOB_DATA (s));
158   }
159 protected:
160   // reference scm_init_ in smob_tag which is sure to be called.  The
161   // constructor, in contrast, may not be called at all in classes
162   // like Smob1.
163   static scm_t_bits smob_tag () { (void) scm_init_; return smob_tag_; }
164   Smob_base () { }
165   static SCM register_ptr (Super *p);
166   static Super *unregister_ptr (SCM obj);
167 private:
168   // Those fallbacks are _only_ for internal use by Smob_base.  They
169   // are characterized by no knowledge about the implemented type
170   // apart from the type's name.  Overriding them as a template
171   // specialization is _not_ intended since a type-dependent
172   // implementation will in general need access to possibly private
173   // parts of the Super class.  So any class-dependent override should
174   // be done by redefining the respective function in the Super class
175   // (where it will mask the private template member) rather than
176   // specializing a different template function/pointer.
177   //
178   // Most default functions are do-nothings.  void init() will
179   // recognize their address when not overriden and will then refrain
180   // altogether from passing the the respective callbacks to GUILE.
181   SCM mark_smob (void);
182   static SCM mark_trampoline (SCM); // Used for calling mark_smob
183   static size_t free_smob (SCM obj);
184   static SCM equal_p (SCM, SCM);
185   int print_smob (SCM, scm_print_state *);
186   static int print_trampoline (SCM, SCM, scm_print_state *);
187
188   // type_p_name_ can be overriden in the Super class with a static
189   // const char [] string.  This requires both a declaration in the
190   // class as well as a single instantiation outside.  Using a
191   // template specialization for supplying a different string name
192   // right in Smob_base<Super> itself seems tempting, but the C++
193   // rules would then require a specialization declaration at the
194   // class definition site as well as a specialization instantiation
195   // in a single compilation unit.  That requires just as much source
196   // code maintenance while being harder to understand and quite
197   // trickier in its failure symptoms when things go wrong.  So we
198   // just use a static zero as "not here" indication.
199   static const int type_p_name_ = 0;
200
201   // LY_DECLARE_SMOB_PROC is used in the Super class definition for
202   // making a smob callable like a function.  Declaration has to be
203   // public.  It may be either be completed with a semicolon in which
204   // case a definition of the member function smob_proc has to be done
205   // outside of the class body, or the semicolon is left off and an
206   // inline function body is added immediately below.  It would be
207   // nice if this were a non-static member function but it would seem
208   // tricky to do the required trampolining for unsmobbing the first
209   // argument of the callback and using it as a this pointer.
210 #define LY_DECLARE_SMOB_PROC(REQ, OPT, VAR, ARGLIST)                    \
211   static const int smob_proc_signature_ = ((REQ)<<8)|((OPT)<<4)|(VAR);  \
212   static SCM smob_proc ARGLIST
213
214   // a separate LY_DEFINE_SMOB_PROC seems sort of pointless as it
215   // would just result in SCM CLASS::smob_proc ARGLIST
216   //
217   // The default case without function functionality is recognized by
218   // smob_proc_signature being -1.
219   static const int smob_proc = 0;
220   static const int smob_proc_signature_ = -1;
221
222 public:
223   static bool is_smob (SCM s)
224   {
225     return SCM_SMOB_PREDICATE (smob_tag (), s);
226   }
227   static SCM smob_p (SCM s)
228   {
229     return is_smob (s) ? SCM_BOOL_T : SCM_BOOL_F;
230   }
231   static Super *unsmob (SCM s)
232   {
233     return is_smob (s) ? Super::unchecked_unsmob (s) : 0;
234   }
235 };
236
237 // Simple smobs
238 template <class Super>
239 class Simple_smob : public Smob_base<Super> {
240 public:
241   static size_t free_smob (SCM obj)
242   {
243     delete Smob_base<Super>::unregister_ptr (obj);
244     return 0;
245   }
246   SCM smobbed_copy () const
247   {
248     Super *p = new Super(*static_cast<const Super *> (this));
249     return Smob_base<Super>::register_ptr (p);
250   }
251 };
252
253 void protect_smob (SCM smob, SCM *prot_cons);
254 void unprotect_smob (SCM smob, SCM *prot_cons);
255
256 template <class Super>
257 class Smob : public Smob_base<Super> {
258 private:
259   SCM self_scm_;
260   SCM protection_cons_;
261   Smob (const Smob<Super> &); // Do not define!  Not copyable!
262 protected:
263   Smob () : self_scm_ (SCM_UNDEFINED), protection_cons_ (SCM_EOL) { };
264 public:
265   static size_t free_smob (SCM obj)
266   {
267     delete Smob_base<Super>::unregister_ptr (obj);
268     return 0;
269   }
270   SCM unprotected_smobify_self ()
271   {
272     SCM s = Smob_base<Super>::register_ptr (static_cast<Super *> (this));
273     self_scm_ = s;
274     return s;
275   }
276   void protect ()
277   {
278     protect_smob (self_scm_, &protection_cons_);
279   }
280   void smobify_self () {
281     protect_smob (unprotected_smobify_self (), &protection_cons_);
282   }
283   SCM unprotect ()
284   {
285     SCM s = self_scm_;
286     unprotect_smob (s, &protection_cons_);
287     return s;
288   }
289   SCM self_scm () const { return self_scm_; }
290 };
291
292 extern bool parsed_objects_should_be_dead;
293 class parsed_dead
294 {
295   static vector<parsed_dead *> elements;
296   SCM data;
297   SCM readout_one ()
298   {
299     SCM res = data;
300     data = SCM_UNDEFINED;
301     return res;
302   }
303 public:
304   parsed_dead () : data (SCM_UNDEFINED)
305   {
306     elements.push_back (this);
307   }
308   void checkin (SCM arg) { data = arg; }
309   static SCM readout ();
310 };
311
312 // This does not appear to work with GUILEv2's garbage collector:
313 // Objects are found in the GC phase but printing them will crash at
314 // least some, so they are apparently not protected in spite of being
315 // included in the GC scans.  So it would appear that scanning smobs
316 // is not equivalent to marking them.  Ugh.
317 #if !defined(NDEBUG) && !GUILEV2
318 #define ASSERT_LIVE_IS_ALLOWED(arg)                                     \
319   do {                                                                  \
320     static parsed_dead pass_here;                                       \
321     if (parsed_objects_should_be_dead)                                  \
322       pass_here.checkin (arg);                                          \
323   } while (0)
324 #else
325 #define ASSERT_LIVE_IS_ALLOWED(arg) do { (void)(arg); }  \
326   while (0)
327 #endif
328
329 #include "smobs.tcc"
330 #endif /* SMOBS_HH */