c++-gtk-utils
extension.h
Go to the documentation of this file.
1 /* Copyright (C) 2014 and 2015 Chris Vine
2 
3 The library comprised in this file or of which this file is part is
4 distributed by Chris Vine under the GNU Lesser General Public
5 License as follows:
6 
7  This library is free software; you can redistribute it and/or
8  modify it under the terms of the GNU Lesser General Public License
9  as published by the Free Software Foundation; either version 2.1 of
10  the License, or (at your option) any later version.
11 
12  This library is distributed in the hope that it will be useful, but
13  WITHOUT ANY WARRANTY; without even the implied warranty of
14  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  Lesser General Public License, version 2.1, for more details.
16 
17  You should have received a copy of the GNU Lesser General Public
18  License, version 2.1, along with this library (see the file LGPL.TXT
19  which came with this source code package in the c++-gtk-utils
20  sub-directory); if not, write to the Free Software Foundation, Inc.,
21  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 
23 However, it is not intended that the object code of a program whose
24 source code instantiates a template from this file or uses macros or
25 inline functions (of any length) should by reason only of that
26 instantiation or use be subject to the restrictions of use in the GNU
27 Lesser General Public License. With that in mind, the words "and
28 macros, inline functions and instantiations of templates (of any
29 length)" shall be treated as substituted for the words "and small
30 macros and small inline functions (ten lines or less in length)" in
31 the fourth paragraph of section 5 of that licence. This does not
32 affect any other reason why object code may be subject to the
33 restrictions in that licence (nor for the avoidance of doubt does it
34 affect the application of section 2 of that licence to modifications
35 of the source code in this file).
36 
37 NOTE: If you incorporate this header file in your code, you will have
38 to link with libguile. libguile is released under the LGPL version 3
39 or later. By linking with libguile your code will therefore be
40 governed by the LPGL version 3 or later, not the LGPL version 2.1 or
41 later.
42 
43 */
44 
45 #ifndef CGU_EXTENSION_H
46 #define CGU_EXTENSION_H
47 
48 /**
49  * @namespace Cgu::Extension
50  * @brief This namespace provides functions to execute scheme code on the guile VM.
51  *
52  * \#include <c++-gtk-utils/extension.h>
53  *
54  * The Extension::exec() and Extension::exec_shared() functions
55  * provided by this library allow any C++ program to execute files
56  * written in the scheme language on the guile VM as part of the C++
57  * runtime. There are a number of reasons why this might be useful:
58  *
59  * @par
60  * - to enable the dynamic behaviour of the program to be altered
61  * without recompilation
62  *
63  * @par
64  * - to provide a plugin system
65  *
66  * @par
67  * - because some things are easier or quicker to do when done in
68  * a dynamically typed language such as scheme
69  *
70  * @par
71  * - because scheme is a nice language to use and highly
72  * extensible
73  *
74  * @par
75  * - with Extension::exec() and Extension::exec_shared(), it is
76  * trivial to do (see the example below)
77  *
78  * To call Extension::exec() or Extension::exec_shared(), guile-2.0 is
79  * required.
80  *
81  * Usage
82  * -----
83  *
84  * Extension::exec() and Extension::exec_shared() take three
85  * arguments. The first is a preamble string, which sets out any top
86  * level definitions which the script file needs to see. This is
87  * mainly intended for argument passing to the script file, but can
88  * comprise any scheme code. It can also be an empty string. The
89  * second is the name of the scheme script file to be executed, with
90  * path. This file can contain scheme code of arbitrary complexity
91  * and length, and can incorporate guile modules and other scheme
92  * files.
93  *
94  * The third argument is a translator. This is a function or callable
95  * object which takes the value to which the scheme file evaluates (in
96  * C++ terms, its return value) as an opaque SCM guile type (it is
97  * actually a pointer to a struct in the guile VM), and converts it to
98  * a suitable C++ representation using functions provided by libguile.
99  * The return value of the translator function comprises the return
100  * value of Extension::exec() and Extension::exec_shared().
101  *
102  * Translators
103  * -----------
104  *
105  * Preformed translators are provided by this library to translate
106  * from scheme's integers, real numbers and strings to C++ longs,
107  * doubles and strings respectively (namely
108  * Extension::integer_to_long(), Extension::real_to_double() and
109  * Extension::string_to_string()), and from any uniform lists of these
110  * to C++ vectors of the corresponding type
111  * (Extension::list_to_vector_long(),
112  * Extension::list_to_vector_double() and
113  * Extension::list_to_vector_string(). There is also a translator for
114  * void return types (Extension::any_to_void()), where the scheme
115  * script is executed for its side effects, perhaps I/O, where the
116  * return value is ignored and any communication necessary is done by
117  * guile exceptions.
118  *
119  * Any guile exception thrown by the code in the scheme file is
120  * trapped by the preformed translators and will be rethrown as an
121  * Extension::GuileException C++ exception. The preformed translators
122  * should suffice for most purposes, but custom translators can be
123  * provided by the user - see further below.
124  *
125  * Example
126  * -------
127  *
128  * Assume the following code is in a file called 'myip.scm'.
129  *
130  * @code
131  * ;; myip.scm
132  *
133  * ;; the following code assumes a top level definition of 'web-ip' is
134  * ;; passed, giving the URL of an IP address reflector
135  *
136  * (use-modules (ice-9 regex)(web uri)(web client))
137  * (let ([uri (build-uri 'http
138  * #:host web-ip
139  * #:port 80
140  * #:path "/")])
141  * (call-with-values
142  * (lambda () (http-get uri))
143  * (lambda (request body)
144  * (match:substring
145  * (string-match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+"
146  * body)))))
147  * @endcode
148  *
149  * This code requires guile >= 2.0.3, and makes a http request to the
150  * reflector, reads the body of the reply and then does a regex search
151  * on it to obtain the address. Courtesy of the good folks at DynDNS
152  * we can obtain our address with this:
153  *
154  * @code
155  * using namespace Cgu;
156  * std::cout << "IP address is: "
157  * << Extension::exec_shared("(define web-ip \"checkip.dyndns.com\")",
158  * "./myip.scm",
159  * &Extension::string_to_string)
160  * << std::endl;
161  * @endcode
162  *
163  * This is easier than doing the same in C++ using, say, libsoup and
164  * std::regex. However it is unsatisfying where we do not want the
165  * code to block waiting for the reply. There are a number of
166  * possible approaches to this, but one is to provide the result to a
167  * glib main loop asynchronously via a Thread::TaskManager object. If
168  * that is done, it is necessary to deal with a case where guile
169  * throws an exception (say because the url does not resolve).
170  * Thread::TaskManager::make_task_packaged_compose() would be suitable
171  * for this because any thrown Extension::GuileException would be
172  * stored in the shared state of a std::packaged_task object:
173  *
174  * @code
175  * using namespace Cgu;
176  * Thread::TaskManager tm{1};
177  * tm.make_task_packaged_compose(
178  * [] () {
179  * return Extension::exec_shared("(define web-ip \"checkip.dyndns.com\")",
180  * "./myip.scm",
181  * &Extension::string_to_string);
182  * },
183  * 0, // supply result to default glib main loop
184  * [] (std::future<std::string>& res) { // the 'when' callback
185  * try {
186  * std:string ip{res.get()};
187  * // publish result in some GTK widget
188  * }
189  * catch (Extension::GuileException& e) {
190  * // display GtkMessageDialog object indicating failure
191  * }
192  * }
193  * );
194  * @endcode
195  *
196  * Extension::exec() and Extension::exec_shared()
197  * ----------------------------------------------
198  *
199  * Extension::exec() isolates the top level definitions of a task,
200  * including definitions in the preamble of a task or imported by
201  * guile's 'use-modules' or 'load' procedures, from the top level
202  * definitions of other tasks started by calls to Extension::exec(),
203  * by calling guile's 'make-fresh-user-module' procedure.
204  * Extension::exec_shared() does not do so: with
205  * Extension::exec_shared(), all scheme tasks executed by calls to
206  * that function will share the same top level. In addition,
207  * Extension::exec() loads the file passed to the function using the
208  * guile 'load' procedure, so that the first time the file is executed
209  * it is compiled into bytecode, whereas Extension::exec_shared()
210  * calls the 'primitive-load' procedure instead, which runs the file
211  * through the guile interpreter without converting it to bytecode.
212  *
213  * The reason for this different behaviour of Extension::exec_shared()
214  * is that, as currently implemented in guile both the
215  * 'make-fresh-user-module' and 'load' procedures leak small amounts
216  * of memory. If a particular program is likely to call
217  * Extension::exec() more than about 5,000 or 10,000 times, it would
218  * be better to use Extension::exec_shared() instead.
219  *
220  * From guile-2.0.2, Extension::exec() and Extension::exec_shared() do
221  * not need to be called only in the main program thread - and in the
222  * above example using a Thread::TaskManager object
223  * Extension::exec_shared() was not. However, one of the consequences
224  * of the behaviour mentioned above is that if
225  * Extension::exec_shared() is to be used instead of
226  * Extension::exec(), either concurrent calls to the function from
227  * different threads should be avoided, or (i) the preambles in calls
228  * to Extension::exec_shared() should be empty and (ii) tasks should
229  * not make clashing top level definitions in some other way,
230  * including by importing clashing definitions using 'use-modules' or
231  * 'load'. The need for Extension::exec_shared() to be called only in
232  * one thread in the example above was the reason why the TaskManager
233  * object in that example was set to have a maximum thread count of 1.
234  * In effect the TaskManager object was a dedicated serial dispatcher
235  * for all scheme tasks.
236  *
237  * The calling by Extension::exec_shared() of 'primitive-load' instead
238  * of 'load' may have some small effect on efficiency. It it best for
239  * the file passed to that function to hand off any complex code to
240  * modules prepared using guile's modules interface (which will be
241  * compiled into bytecode), and which are then loaded using
242  * 'use-modules' the first time Extension::exec_shared() is called, or
243  * by having the first call to Extension::exec_shared() (and only the
244  * first call) import any needed files into the top level using
245  * 'load'.
246  *
247  * Note that some guile global state may be shared between tasks
248  * whether Extension::exec() or Extension::exec_shared() is used. For
249  * example, if the guile 'add-to-load-path' procedure is called to add
250  * a local directory to the search path used by 'use-modules' or
251  * 'load', that will have effect for all other tasks.
252  *
253  * Other thread safety points
254  * --------------------------
255  *
256  * Leaving aside what has been said above, there are a few other
257  * issues to keep in mind if executing scheme code in more than one
258  * thread.
259  *
260  * First, the initialization of guile < 2.0.10 is not thread safe.
261  * One thread needs to have called Extension::exec() or
262  * Extension::exec_shared() once and returned before any other threads
263  * call the function. This can be achieved by the simple expedient of
264  * executing the statement:
265  *
266  * @code
267  * Extension::exec_shared("", "", &Extension::any_to_void);
268  * @endcode
269  *
270  * and waiting for it to return before any tasks are added to a
271  * TaskManager object running more than one thread. This issue is
272  * fixed in guile-2.0.10. However there is a further snag. Certain
273  * aspects of guile module loading are not thread safe. One way
274  * around this is to load all the modules that tasks may use in
275  * advance, by loading the modules in the preamble of the above
276  * statement (or to have that statement execute a file which loads the
277  * modules). If that is done, it should be fine afterwards to run
278  * Extension::exec() (or Extension::exec_shared() if clashing top
279  * level definitions are avoided as mentioned above) on a TaskManager
280  * object running any number of threads, or on a Thread::Future object
281  * or std::async() task. (However, note that if using
282  * Extension::exec() the modules would need to be reloaded in each
283  * task in order to make them visible to the task, but that would be
284  * done safely if they have previously been loaded in another task.)
285  *
286  * This issue is likely to be fixed in a future version of guile.
287  *
288  * If a C++ program is to run guile tasks on a TaskManager object
289  * having a maximum thread count greater than one (or in more than one
290  * thread in some other way), one other point should be noted. When a
291  * scheme file is executed for the first time by a user by being
292  * passed as the second argument of Extension::exec() (or by having
293  * 'load' applied to it in some other way), it will be compiled into
294  * byte code, the byte code will then be cached on the file system for
295  * that and subsequent calls, and the byte code then executed. Bad
296  * things might happen if concurrent calls to Extension::exec(), or to
297  * the 'load' or 'use-modules' procedures, are made in respect of the
298  * same scheme file for the "first" time, if there might be a race as
299  * to which of them is the "first" call in respect of the file: that
300  * is, if it causes two or more threads to try to compile the same
301  * file into byte code concurrently. This is only an issue the first
302  * time a particular user executes a scheme file, and can be avoided
303  * (amongst other ways) by having the C++ program concerned
304  * pre-compile the relevant scheme file before Extension::exec() or
305  * Extension::exec_shared() is first called, by means of the 'guild
306  * compile [filename]' command. The following gives more information
307  * about compilation: <A
308  * HREF="http://www.gnu.org/software/guile/manual/html_node/Compilation.html#Compilation">
309  * Compiling Scheme Code</A>
310  *
311  * Licence
312  * -------
313  *
314  * The c++-gtk-utils library (and this c++-gtk-utils/extension.h
315  * header file) follows glib and GTK+ by being released under the LGPL
316  * version 2.1 or later. libguile is released under the LGPL version
317  * 3 or later. The c++-gtk-utils library object code does not link to
318  * libguile, nor does it incorporate anything in the
319  * c++-gtk-utils/extension.h header. Instead
320  * c++-gtk-utils/extension.h contains all its code as a separate
321  * unlinked header for any program which wants to include it (this is
322  * partly because some of it comprises template functions).
323  *
324  * There are two consequences. If you want to use Extension::exec()
325  * or Extension::exec_shared(), the program which calls it will need
326  * to link itself explicitly with libguile as well as c++-gtk-utils,
327  * and to do that will need to use pkg-config to obtain libguile's
328  * cflags and libs particulars (its pkg-config file is guile-2.0.pc).
329  * This library does NOT do that for you. Secondly, by linking with
330  * libguile you will be governed by the LGPL version 3 or later,
331  * instead of the LGPL version 2.1 or later, with respect to that
332  * linking. That's fine (there is nothing wrong with the LGPL version
333  * 3 and this library permits that) but you should be aware of it.
334  * The scheme code in guile's scheme level modules is also in the main
335  * released under the LGPL version 3 or later ("in the main" because
336  * readline.scm, comprised in the readline module, is released under
337  * the GPL version 3 or later).
338  *
339  * Custom translators
340  * ------------------
341  *
342  * Any function or callable object which translates from an opaque SCM
343  * value to a suitable C++ representation can be passed as the third
344  * argument of Extension::exec() or Extension::exec_shared(). C++
345  * type deduction on template resolution will take care of everything
346  * else. The translator can execute any functions offered by
347  * libguile, because when the translator is run the program is still
348  * in guile mode. The fulsome guile documentation sets out the
349  * libguile functions which are callable in C/C++ code.
350  *
351  * The first call in a custom translator should normally be to the
352  * Extension::rethrow_guile_exception() function. This function tests
353  * whether a guile exception arose in executing the scheme file, and
354  * throws a C++ exception if it did. The preformed translators in
355  * extension.h provide worked examples of how a custom translator
356  * might be written.
357  *
358  * If something done in a custom translator were to raise a guile
359  * exception, the library implementation would handle it and a C++
360  * exception would be generated in its place in Extension::exec() or
361  * Extension::exec_shared(). However, a custom translator should not
362  * allow a guile exception arising from calls to libguile made by it
363  * to exit a C++ scope in which the translator has constructed a local
364  * C++ object which is not trivially destructible: that would give
365  * rise to undefined behaviour, with the likely result that the C++
366  * object's destructor would not be called. One approach to this
367  * (adopted in the preformed translators) is to allocate on free store
368  * all local C++ objects to be constructed in the translator which are
369  * not trivially destructible, and to manage their lifetimes manually
370  * using local C++ try/catch blocks rather than RAII, with dynwind
371  * unwind handlers to release memory were there to be a guile
372  * exception (but note that no C++ exception should transit out of a
373  * scm_dynwind_begin()/scm_dynwind_end() pair). It is also a good
374  * idea to test for any condition which might cause a guile exception
375  * to be raised in the translator in the first place, and throw a C++
376  * exception beforehand. Then the only condition which might cause a
377  * guile exception to occur in the translator is an out-of-memory
378  * condition, which is highly improbable in a translator as the
379  * translator is run after the guile task has completed. Heap
380  * exhaustion in such a case probably spells doom for the program
381  * concerned anyway, if it has other work to do.
382  *
383  * Scheme
384  * ------
385  * If you want to learn more about scheme, these are useful sources:
386  * <P>
387  * <A HREF="http://www.gnu.org/software/guile/manual/html_node/Hello-Scheme_0021.html"> Chapter 3 of the Guile Manual</A>
388  * (the rest of the manual is also good reading).</P>
389  * <P>
390  * <A HREF="http://www.scheme.com/tspl4/">The Scheme Programming Language, 4th edition</A></P>
391  */
392 
393 #include <string>
394 #include <vector>
395 #include <exception>
396 #include <memory> // for std::unique_ptr
397 #include <type_traits> // for std::result_of
398 #include <limits> // for std::numeric_limits
399 #include <utility> // for std::forward and std::move
400 #include <new> // for std::bad_alloc
401 
402 #include <stddef.h> // for size_t
403 #include <stdlib.h> // for free()
404 #include <string.h> // for strlen() and strncmp()
405 
406 #include <glib.h>
407 
409 #include <c++-gtk-utils/callback.h>
410 #include <c++-gtk-utils/thread.h>
411 #include <c++-gtk-utils/mutex.h>
413 
414 #include <libguile.h>
415 
416 
417 #ifndef DOXYGEN_PARSING
418 namespace Cgu {
419 
420 namespace Extension {
421 
422 struct FormatArgs {
423  SCM text;
424  SCM rest;
425 };
426 
427 enum VectorDeleteType {Long, Double, String};
428 
429 struct VectorDeleteArgs {
430  VectorDeleteType type;
431  void* vec;
432 };
433 
434 // defined in extension_helper.cpp
435 extern Cgu::Thread::Mutex* get_user_module_mutex() noexcept;
436 extern bool init_mutex() noexcept;
437 
438 } // namespace Extension
439 
440 } // namespace Cgu
441 
442 namespace {
443 extern "C" {
444  inline SCM cgu_format_try_handler(void* data) {
445  using Cgu::Extension::FormatArgs;
446  FormatArgs* format_args = static_cast<FormatArgs*>(data);
447  return scm_simple_format(SCM_BOOL_F, format_args->text, format_args->rest);
448  }
449  inline SCM cgu_format_catch_handler(void*, SCM, SCM) {
450  return SCM_BOOL_F;
451  }
452  inline void* cgu_guile_wrapper(void* data) {
453  try {
454  static_cast<Cgu::Callback::Callback*>(data)->dispatch();
455  }
456  // an elipsis catch block is fine as thread cancellation is
457  // blocked. We can only enter this block if assigning to one of
458  // the exception strings in the callback has thrown
459  // std::bad_alloc. For that case we return a non-NULL pointer to
460  // indicate error (the 'data' argument is convenient and
461  // guaranteed to be standard-conforming for this).
462  catch (...) {
463  return data;
464  }
465  return 0;
466  }
467  inline void cgu_delete_vector(void* data) {
468  using Cgu::Extension::VectorDeleteArgs;
469  VectorDeleteArgs* args = static_cast<VectorDeleteArgs*>(data);
470  switch (args->type) {
471  case Cgu::Extension::Long:
472  delete static_cast<std::vector<long>*>(args->vec);
473  break;
474  case Cgu::Extension::Double:
475  delete static_cast<std::vector<double>*>(args->vec);
476  break;
477  case Cgu::Extension::String:
478  delete static_cast<std::vector<std::string>*>(args->vec);
479  break;
480  default:
481  g_critical("Incorrect argument passed to cgu_delete_vector");
482  }
483  delete args;
484  }
485  inline void cgu_unlock_module_mutex(void*) {
486  // this cannot give rise to an allocation or mutex error -
487  // we must have been called init_mutex() first
488  Cgu::Extension::get_user_module_mutex()->unlock();
489  }
490 } // extern "C"
491 } // unnamed namespace
492 #endif // DOXYGEN_PARSING
493 
494 namespace Cgu {
495 
496 namespace Extension {
497 
498 class GuileException: public std::exception {
499  Cgu::GcharSharedHandle message;
500  Cgu::GcharSharedHandle guile_message;
501 public:
502  virtual const char* what() const throw() {return (const char*)message.get();}
503  const char* guile_text() const throw() {return (const char*)guile_message.get();}
504  GuileException(const char* msg):
505  message(g_strdup_printf(u8"Cgu::Extension::GuileException: %s", msg)),
506  guile_message(g_strdup(msg)) {}
507  ~GuileException() throw() {}
508 };
509 
510 class ReturnValueError: public std::exception {
511  Cgu::GcharSharedHandle message;
512  Cgu::GcharSharedHandle err_message;
513 public:
514  virtual const char* what() const throw() {return (const char*)message.get();}
515  const char* err_text() const throw() {return (const char*)err_message.get();}
516  ReturnValueError(const char* msg):
517  message(g_strdup_printf(u8"Cgu::Extension::ReturnValueError: %s", msg)),
518  err_message(g_strdup(msg)) {}
519  ~ReturnValueError() throw() {}
520 };
521 
522 class WrapperError: public std::exception {
523  Cgu::GcharSharedHandle message;
524 public:
525  virtual const char* what() const throw() {return (const char*)message.get();}
526  WrapperError(const char* msg):
527  message(g_strdup_printf(u8"Cgu::Extension::WrapperError: %s", msg)) {}
528  ~WrapperError() throw() {}
529 };
530 
531 #ifndef DOXYGEN_PARSING
532 
533 // we might as well take 'translator' by collapsible reference. If it
534 // is handed a rvalue function object, it will be implicitly converted
535 // to lvalue (and if necessary constructed as such) in order to take a
536 // lvalue reference on lambda construction. If it is already a
537 // lvalue, it will be passed through seamlessly.
538 template <class Ret, class Translator>
539 Ret exec_impl(const std::string& preamble,
540  const std::string& file,
541  Translator&& translator,
542  bool shared) {
543 
545 
546  std::string loader;
547  loader += preamble;
548  if (!file.empty()) {
549  if (shared)
550  loader += u8"((lambda ()";
551  loader += u8"(catch "
552  "#t"
553  "(lambda ()"
554  "(";
555  if (shared)
556  loader += u8"primitive-load \"";
557  else
558  loader += u8"load \"";
559  loader += file;
560  loader += u8"\"))"
561  "(lambda (key . details)"
562  "(cons \"***cgu-guile-exception***\" (cons key details))))";
563  if (shared)
564  loader += u8"))";
565  }
566 
567  Ret retval;
568  bool result = false;
569  std::string guile_except;
570  std::string guile_ret_val_err;
571  std::string gen_err;
572 
573  // we construct a Callback::Callback object here to perform type
574  // erasure. Otherwise we would have to pass scm_with_guile() a
575  // function pointer to a function templated on Translator and Ret,
576  // which must have C++ language linkage (§14/4 of C++ standard).
577  // Technically this would give undefined behaviour as
578  // scm_with_guile() expects a function pointer with C language
579  // linkage, although gcc and clang would accept it. The whole of
580  // this callback will be executed in guile mode via
581  // cgu_guile_wrapper(), so it can safely call libguile functions
582  // (provided that a translator does not allow any guile exceptions
583  // to escape a C++ scope with local objects which are not trivially
584  // destructible). It is also safe to pass 'translator', 'retval',
585  // 'loader', 'result' and the exception strings to it by reference,
586  // because scm_with_guile() will block until it has completed
587  // executing. cgu_guile_wrapper() will trap any std::bad_alloc
588  // exception thrown by the string assignments in the catch blocks in
589  // this lambda. This lambda is safe against a jump to an exit from
590  // scm_with_guile() arising from a native guile exception in
591  // translator, because its body has no objects in local scope
592  // requiring destruction.
593  std::unique_ptr<Cgu::Callback::Callback> cb(Cgu::Callback::lambda<>([&] () -> void {
594  SCM scm;
595  if (shared) {
596  scm = scm_eval_string_in_module(scm_from_utf8_string(loader.c_str()),
597  scm_c_resolve_module("guile-user"));
598  }
599  else {
600  if (!init_mutex())
601  throw std::bad_alloc(); // this will be caught in cgu_guile_wrapper()
602 
603  scm_dynwind_begin(scm_t_dynwind_flags(0));
604  scm_dynwind_unwind_handler(&cgu_unlock_module_mutex, 0, SCM_F_WIND_EXPLICITLY);
605  get_user_module_mutex()->lock(); // won't throw
606  SCM new_mod = scm_call_0(scm_c_public_ref("guile", "make-fresh-user-module"));
607  scm_dynwind_end();
608 
609  scm = scm_eval_string_in_module(scm_from_utf8_string(loader.c_str()),
610  new_mod);
611  }
612 
613  // have a dynwind context and async block while translator is
614  // executing. This is to cater for the pathological case of
615  // the scheme script having set up a signal handler which
616  // might throw a guile exception, or having chained a series
617  // of system asyncs which are still queued for action, which
618  // might otherwise cause the translator to trigger a guile
619  // exception while a non-trivially destructible object is in
620  // the local scope of translator. (Highly unlikely, but easy
621  // to deal with.) This is entirely safe as no C++ exception
622  // arising from the translator can transit across the dynamic
623  // context in this function - see below. So we have (i) no
624  // C++ exception can transit across a guile dynamic context,
625  // and (ii) no guile exception can escape out of a local C++
626  // scope by virtue of an async executing (it might still
627  // escape with a non-trivially destructible object in
628  // existence if a custom translator has not been written
629  // correctly, but there is nothing we can do about that).
630  // Note that some guile installations do not link
631  // scm_dynwind_block_asyncs() correctly - this is tested at
632  // configuration time.
633 #ifndef CGU_GUILE_HAS_BROKEN_LINKING
634  scm_dynwind_begin(scm_t_dynwind_flags(0));
635  scm_dynwind_block_asyncs();
636 #endif
637  // we cannot use std::exception_ptr here to store a C++
638  // exception object, because std::exception_ptr is not
639  // trivially destructible and a guile exception in
640  // 'translator' could jump out of this scope to its
641  // continuation in scm_with_guile()
642  bool badalloc = false;
643  try {
644  retval = translator(scm);
645  result = true; // this will detect any guile exception in
646  // the preamble or 'translator' which causes
647  // scm_with_guile() to return prematurely.
648  // We could have done it instead by reversing
649  // the return values of cgu_guile_wrapper
650  // (non-NULL for success and NULL for
651  // failure) because scm_with_guile() returns
652  // NULL if it exits on an uncaught guile
653  // exception, but this approach enables us to
654  // discriminate between a C++ memory
655  // exception in the wrapper and a guile
656  // exception in the preamble or 'translator',
657  // at a minimal cost of one assignment to a
658  // bool.
659  }
660  catch (GuileException& e) {
661  try {
662  guile_except = e.guile_text();
663  }
664  catch (...) {
665  badalloc = true;
666  }
667  }
668  catch (ReturnValueError& e) {
669  try {
670  guile_ret_val_err = e.err_text();
671  }
672  catch (...) {
673  badalloc = true;
674  }
675  }
676  catch (std::exception& e) {
677  try {
678  gen_err = e.what();
679  }
680  catch (...) {
681  badalloc = true;
682  }
683  }
684  catch (...) {
685  try {
686  gen_err = u8"C++ exception thrown in cgu_guile_wrapper()";
687  }
688  catch (...) {
689  badalloc = true;
690  }
691  }
692 #ifndef CGU_GUILE_HAS_BROKEN_LINKING
693  scm_dynwind_end();
694 #endif
695  if (badalloc) throw std::bad_alloc(); // this will be caught in cgu_guile_wrapper()
696  }));
697  // cgu_guile_wrapper(), and so scm_with_guile() will return a
698  // non-NULL value if assigning to one of the exception description
699  // strings above threw std::bad_alloc
700  if (scm_with_guile(&cgu_guile_wrapper, cb.get()))
701  throw WrapperError(u8"cgu_guile_wrapper() has trapped std::bad_alloc");
702  if (!guile_except.empty())
703  throw GuileException(guile_except.c_str());
704  if (!guile_ret_val_err.empty())
705  throw ReturnValueError(guile_ret_val_err.c_str());
706  if (!gen_err.empty())
707  throw WrapperError(gen_err.c_str());
708  if (!result)
709  throw WrapperError(u8"the preamble or translator threw a native guile exception");
710  return retval;
711 }
712 
713 #endif // DOXYGEN_PARSING
714 
715 /**
716  * This function is called by Extension::rethrow_guile_exception()
717  * where the scheme code executed by Extension::exec() or
718  * Extension::exec_shared() has exited with a guile exception. It
719  * converts the raw guile exception information represented by the
720  * 'key' and 'args' arguments of a guile catch handler to a more
721  * readable form. It is made available as part of the public
722  * interface so that any custom translators can also use it if they
723  * choose to provide their own catch expressions. This function does
724  * not throw any C++ exceptions. No native guile exception will arise
725  * in this function and so cause guile to jump out of it assuming no
726  * guile out-of-memory condition occurs (and given that this function
727  * is called after a guile extension task has completed, such a
728  * condition is very improbable). It is thread safe, but see the
729  * comments above about the thread safety of Extension::exec() and
730  * Extension::exec_shared().
731  *
732  * @param key An opaque guile SCM object representing a symbol
733  * comprising the 'key' argument of the exception handler of a guile
734  * catch expression.
735  * @param args An opaque guile SCM object representing a list
736  * comprising the 'args' argument of the exception handler of a guile
737  * catch expression.
738  * @return An opaque guile SCM object representing a guile string.
739  *
740  * Since 2.0.22 and 2.2.5
741  */
742 inline SCM exception_to_string(SCM key, SCM args) noexcept {
743  // The args of most exceptions thrown by guile are in the following format:
744  // (car args) - a string comprising the name of the procedure generating the exception
745  // (cadr args) - a string containing text, possibly with format directives (escape sequences)
746  // (caddr args) - a list containing items matching the format directives, or #f if none
747  // (cadddr args) - (not used here) a list of additional objects (eg the errno for some errors),
748  // or #f if none
749  SCM ret = SCM_BOOL_F;
750  int length = scm_to_int(scm_length(args));
751  if (length) {
752  SCM first = scm_car(args);
753  if (scm_is_true(scm_string_p(first))) {
754  // if a single user string, output it
755  if (length == 1) {
756  ret = scm_string_append(scm_list_4(scm_from_utf8_string(u8"Exception "),
757  scm_symbol_to_string(key),
758  scm_from_utf8_string(u8": "),
759  first));
760  }
761  else { // length > 1
762  SCM second = scm_cadr(args);
763  if (scm_is_true(scm_string_p(second))) {
764  // we should have a standard guile exception string, as above
765  SCM text = scm_string_append(scm_list_n(scm_from_utf8_string(u8"Exception "),
766  scm_symbol_to_string(key),
767  scm_from_utf8_string(u8" in procedure "),
768  first,
769  scm_from_utf8_string(u8": "),
770  second,
771  SCM_UNDEFINED));
772  if (length == 2)
773  ret = text;
774  else { // length > 2
775  SCM third = scm_caddr(args);
776  if (scm_is_false(third))
777  ret = text;
778  else if (scm_is_true(scm_list_p(third))) {
779  FormatArgs format_args = {text, third};
780  ret = scm_internal_catch(SCM_BOOL_T,
781  &cgu_format_try_handler,
782  &format_args,
783  &cgu_format_catch_handler,
784  0);
785  }
786  }
787  }
788  }
789  }
790  }
791  // fall back to generic formatting if first or second elements of
792  // args is not a string or simple-format failed above
793  if (scm_is_false(ret)) {
794  // there is no need for a catch block: we know simple-format
795  // cannot raise an exception here
796  ret = scm_simple_format(SCM_BOOL_F,
797  scm_from_utf8_string(u8"Exception ~S: ~S"),
798  scm_list_2(key, args));
799  }
800  return ret;
801 }
802 
803 /**
804  * This function tests whether a guile exception arose in executing a
805  * scheme extension file, and throws Cgu::Extension::GuileException if
806  * it did. It is intended for use by custom translators, as the first
807  * thing the translator does. It is thread safe, but see the comments
808  * above about the thread safety of Extension::exec() and
809  * Extension::exec_shared().
810  *
811  * @param scm An opaque guile SCM object representing the value to
812  * which the extension file passed to Extension::exec() or
813  * Extension::exec_shared() evaluated.
814  * @exception std::bad_alloc This function might throw std::bad_alloc
815  * if memory is exhausted and the system throws in that case.
816  * @exception Cgu::Extension::GuileException This exception will be
817  * thrown if the scheme code executed in the extension file passed to
818  * Extension::exec() or Extension::exec_shared() threw a guile
819  * exception. Cgu::Extension::GuileException::what() will give
820  * particulars of the guile exception thrown, in UTF-8 encoding.
821  * @note No native guile exception will arise in this function and so
822  * cause guile to jump out of it if no guile out-of-memory condition
823  * occurs (given that this function is called after a guile extension
824  * task has completed, such a condition is very improbable).
825  *
826  * Since 2.0.22 and 2.2.5
827  */
828 inline void rethrow_guile_exception(SCM scm) {
829  // guile exceptions are always presented to this function as a
830  // scheme list
831  if (scm_is_false(scm_list_p(scm))
832  || scm_is_true(scm_null_p(scm))) return;
833  SCM first = scm_car(scm);
834  if (scm_is_true(scm_string_p(first))) {
835  size_t len;
836  const char* text = 0;
837  // nothing in this function should throw a guile exception unless
838  // there is a guile out-of-memory exception (which is extremely
839  // improbable). However, let's cover ourselves in case
840  scm_dynwind_begin(scm_t_dynwind_flags(0));
841  char* car = scm_to_utf8_stringn(first, &len);
842  // there may be a weakness in guile's implementation here: if
843  // calling scm_dynwind_unwind_handler() were to give rise to an
844  // out-of-memory exception before the handler is set up by it,
845  // then we could leak memory allocated from the preceding call to
846  // scm_to_utf8_stringn(). Whether that could happen is not
847  // documented, but because (a) it is so improbable, and (b) once
848  // we are in out-of-memory land we are already in severe trouble
849  // and glib is likely to terminate the program at some point
850  // anyway, it is not worth troubling ourselves over.
851  scm_dynwind_unwind_handler(&free, car, scm_t_wind_flags(0));
852  if (len == strlen(u8"***cgu-guile-exception***")
853  && !strncmp(car, u8"***cgu-guile-exception***", len)) {
854  SCM str = exception_to_string(scm_cadr(scm), scm_cddr(scm));
855  // we don't need a dynwind handler for 'text' because nothing
856  // after the call to scm_to_utf8_stringn() can cause a guile
857  // exception to be raised
858  text = scm_to_utf8_stringn(str, &len);
859  }
860  // all done - no more guile exceptions are possible in this
861  // function after this so end the dynamic context, take control of
862  // the memory by RAII and if necessary throw a C++ exception
863  scm_dynwind_end();
864  std::unique_ptr<char, Cgu::CFree> up_car(car);
865  std::unique_ptr<const char, Cgu::CFree> up_text(text);
866  // if 'text' is not NULL, 'len' contains its length in bytes
867  if (text) throw GuileException(std::string(text, len).c_str());
868  }
869 }
870 
871 /**
872  * A translator function which can be passed to the third argument of
873  * Extension::exec() or Extension::exec_shared(). It converts from a
874  * homogeneous scheme list of integers to a C++ representation of
875  * std::vector<long>. It is thread safe, but see the comments above
876  * about the thread safety of Extension::exec() and
877  * Extension::exec_shared().
878  *
879  * @param scm An opaque guile SCM object representing the value to
880  * which the extension file passed to Extension::exec() or
881  * Extension::exec_shared() evaluated, where that value is a
882  * homogeneous list of integers.
883  * @return The std::vector<long> representation.
884  * @exception std::bad_alloc This function might throw std::bad_alloc
885  * if memory is exhausted and the system throws in that case, or if
886  * the length of the input list exceeds std::vector::max_size().
887  * @exception Cgu::Extension::GuileException This exception will be
888  * thrown if the scheme code in the extension file passed to
889  * Extension::exec() or Extension::exec_shared() caused a guile
890  * exception to be thrown. Cgu::Extension::GuileException::what()
891  * will give particulars of the guile exception thrown, in UTF-8
892  * encoding.
893  * @exception Cgu::Extension::ReturnValueError This exception will be
894  * thrown if the scheme code in the extension file passed to
895  * Extension::exec() or Extension::exec_shared() does not evaluate to
896  * the type expected by the translator, or it is out of range for a
897  * long. Cgu::Extension::ReturnValueError::what() will give further
898  * particulars, in UTF-8 encoding.
899  * @note No native guile exception will arise in this function and so
900  * cause guile to jump out of it unless a guile out-of-memory
901  * condition occurs (given that this function is called after a guile
902  * extension task has completed, such a condition is very improbable)
903  * or the length of the input list exceeds SIZE_MAX (the maximum value
904  * of std::size_t). If such an exception were to arise, the
905  * implementation would handle it and a C++ exception would be
906  * generated in its place in Extension::exec() or
907  * Extension::exec_shared().
908  *
909  * Since 2.0.22 and 2.2.5
910  */
911 inline std::vector<long> list_to_vector_long(SCM scm) {
913  if (scm_is_false(scm_list_p(scm)))
914  throw ReturnValueError(u8"scheme code did not evaluate to a list\n");
915 
916  // nothing in this function should throw a guile exception unless
917  // there is a guile out-of-memory exception (which is extremely
918  // improbable). However, let's cover ourselves in case.
919  scm_dynwind_begin(scm_t_dynwind_flags(0));
920  // we cannot have a std::vector object in a scope where a guile
921  // exception might be raised because it has a non-trivial
922  // destructor, nor can we use RAII. Instead allocate on free store
923  // and manage the memory by hand until we can no longer jump on a
924  // guile exception. In addition we cannot store a C++ exception
925  // using std::exception_ptr because std::exception_ptr is not
926  // trivially destructible.
927  bool badalloc = false;
928  const char* rv_error = 0;
929  std::vector<long>* res = 0;
930  VectorDeleteArgs* args = 0;
931  try {
932  // it doesn't matter if the second allocation fails, as we clean
933  // up at the end if there is no guile exception, and if both
934  // allocations succeed and there were to be a subsequent guile
935  // exception, cgu_delete_vector cleans up
936  res = new std::vector<long>;
937  // allocate 'args' on free store, because the continuation in
938  // which it executes will be up the stack
939  args = new VectorDeleteArgs{Long, res};
940  }
941  catch (...) {
942  badalloc = true;
943  }
944  if (!badalloc) {
945  // there may be a weakness in guile's implementation here: if
946  // calling scm_dynwind_unwind_handler() were to give rise to a
947  // guile out-of-memory exception before the handler is set up by
948  // it, then we could leak memory allocated from the preceding new
949  // expressions. Whether that could happen is not documented by
950  // guile, but because (a) it is so improbable, and (b) once we are
951  // in out-of-memory land we are already in severe trouble and glib
952  // is likely to terminate the program at some point anyway, it is
953  // not worth troubling ourselves over.
954  scm_dynwind_unwind_handler(&cgu_delete_vector, args, scm_t_wind_flags(0));
955  // convert the list to a guile vector so we can access its items
956  // efficiently in a for loop. This conversion is reasonably
957  // efficient, in the sense that an ordinary guile vector is an
958  // array of pointers, pointing to the same scheme objects that the
959  // list refers to
960  SCM guile_vec = scm_vector(scm);
961 
962  // std::vector::size_type is the same as size_t with the standard
963  // allocators (but if we were to get a silent narrowing conversion
964  // on calling std::vector::reserve() below, that doesn't matter -
965  // instead if 'length' is less than SIZE_MAX but greater than the
966  // maximum value of std::vector::size_type, at some point a call
967  // to std::vector::push_back() below would throw and be caught,
968  // and this function would end up rethrowing it as std::bad_alloc.
969  // If in a particular implementation SIZE_MAX exceeds
970  // std::vector::max_size(), a std::length_error exception would be
971  // thrown by reserve() where max_size() is exceeded. On all
972  // common implementations, max_size() is equal to SIZE_MAX, but
973  // were such an exception to arise it would be swallowed (see
974  // below) and then rethrown by this function as std::bad_alloc.
975  // If 'length' is greater than SIZE_MAX, a guile out-of-range
976  // exception would be thrown by scm_to_size_t() which would be
977  // rethrown by Cgu:Extension::exec() or
978  // Cgu::Exception::exec_shared as a Cgu::Extension::WrapperError
979  // C++ exception. This is nice to know but in practice such large
980  // lists would be unusably slow and a memory exception would be
981  // reached long before std::vector::max_size() or SIZE_MAX are
982  // exceeded.
983  size_t length = scm_to_size_t(scm_vector_length(guile_vec));
984  try {
985  res->reserve(length);
986  }
987  catch (...) {
988  badalloc = true;
989  }
990  for (size_t count = 0;
991  count < length && !rv_error && !badalloc;
992  ++count) {
993  SCM item = scm_vector_ref(guile_vec, scm_from_size_t(count));
994  if (scm_is_false(scm_integer_p(item)))
995  rv_error = u8"scheme code did not evaluate to a homogeneous list of integer\n";
996  else {
997  SCM min = scm_from_long(std::numeric_limits<long>::min());
998  SCM max = scm_from_long(std::numeric_limits<long>::max());
999  if (scm_is_false(scm_leq_p(item, max)) || scm_is_false(scm_geq_p(item, min)))
1000  rv_error = u8"scheme code evaluated out of range for long\n";
1001  else {
1002  try {
1003  res->push_back(scm_to_long(item));
1004  }
1005  catch (...) {
1006  badalloc = true;
1007  }
1008  }
1009  }
1010  }
1011  }
1012  // all done - no more guile exceptions are possible in this function
1013  // after this so end the dynamic context, take control of the memory
1014  // by RAII and if necessary throw a C++ exception
1015  scm_dynwind_end();
1016  std::unique_ptr<std::vector<long>> up_res(res);
1017  std::unique_ptr<VectorDeleteArgs> up_args(args);
1018  if (badalloc) throw std::bad_alloc();
1019  if (rv_error) throw ReturnValueError(rv_error);
1020  // neither gcc-4.9 nor clang-3.4 will optimize with RVO or move
1021  // semantics here, so force it by hand
1022  return std::move(*res);
1023 }
1024 
1025 /**
1026  * A translator function which can be passed to the third argument of
1027  * Extension::exec() or Extension::exec_shared(). It converts from a
1028  * homogeneous scheme list of real numbers to a C++ representation of
1029  * std::vector<double>. It is thread safe, but see the comments above
1030  * about the thread safety of Extension::exec() and
1031  * Extension::exec_shared().
1032  *
1033  * @param scm An opaque guile SCM object representing the value to
1034  * which the extension file passed to Extension::exec() or
1035  * Extension::exec_shared() evaluated, where that value is a
1036  * homogeneous list of real numbers.
1037  * @return The std::vector<double> representation.
1038  * @exception std::bad_alloc This function might throw std::bad_alloc
1039  * if memory is exhausted and the system throws in that case, or if
1040  * the length of the input list exceeds std::vector::max_size().
1041  * @exception Cgu::Extension::GuileException This exception will be
1042  * thrown if the scheme code in the extension file passed to
1043  * Extension::exec() or Extension::exec_shared() caused a guile
1044  * exception to be thrown. Cgu::Extension::GuileException::what()
1045  * will give particulars of the guile exception thrown, in UTF-8
1046  * encoding.
1047  * @exception Cgu::Extension::ReturnValueError This exception will be
1048  * thrown if the scheme code in the extension file passed to
1049  * Extension::exec() or Extension::exec_shared() does not evaluate to
1050  * the type expected by the translator, or it is out of range for a
1051  * double. Cgu::Extension::ReturnValueError::what() will give further
1052  * particulars, in UTF-8 encoding.
1053  * @note 1. Prior to versions 2.0.25 and 2.2.8, this translator had a
1054  * bug which caused an out-of-range Cgu::Extension::ReturnValueError
1055  * to be thrown if any of the numbers in the list to which the scheme
1056  * code in the extension file evaluated was 0.0 or a negative number.
1057  * This was fixed in versions 2.0.25 and 2.2.8.
1058  * @note 2. No native guile exception will arise in this function and
1059  * so cause guile to jump out of it unless a guile out-of-memory
1060  * condition occurs (given that this function is called after a guile
1061  * extension task has completed, such a condition is very improbable)
1062  * or the length of the input list exceeds SIZE_MAX (the maximum value
1063  * of std::size_t). If such an exception were to arise, the
1064  * implementation would handle it and a C++ exception would be
1065  * generated in its place in Extension::exec() or
1066  * Extension::exec_shared().
1067  *
1068  * Since 2.0.22 and 2.2.5
1069  */
1070 inline std::vector<double> list_to_vector_double(SCM scm) {
1072  if (scm_is_false(scm_list_p(scm)))
1073  throw ReturnValueError(u8"scheme code did not evaluate to a list\n");
1074 
1075  // nothing in this function should throw a guile exception unless
1076  // there is a guile out-of-memory exception (which is extremely
1077  // improbable). However, let's cover ourselves in case.
1078  scm_dynwind_begin(scm_t_dynwind_flags(0));
1079  // we cannot have a std::vector object in a scope where a guile
1080  // exception might be raised because it has a non-trivial
1081  // destructor, nor can we use RAII. Instead allocate on free store
1082  // and manage the memory by hand until we can no longer jump on a
1083  // guile exception. In addition we cannot store a C++ exception
1084  // using std::exception_ptr because std::exception_ptr is not
1085  // trivially destructible.
1086  bool badalloc = false;
1087  const char* rv_error = 0;
1088  std::vector<double>* res = 0;
1089  VectorDeleteArgs* args = 0;
1090  try {
1091  // it doesn't matter if the second allocation fails, as we clean
1092  // up at the end if there is no guile exception, and if both
1093  // allocations succeed and there were to be a subsequent guile
1094  // exception, cgu_delete_vector cleans up
1095  res = new std::vector<double>;
1096  // allocate 'args' on free store, because the continuation in
1097  // which it executes will be up the stack
1098  args = new VectorDeleteArgs{Double, res};
1099  }
1100  catch (...) {
1101  badalloc = true;
1102  }
1103  if (!badalloc) {
1104  // there may be a weakness in guile's implementation here: if
1105  // calling scm_dynwind_unwind_handler() were to give rise to a
1106  // guile out-of-memory exception before the handler is set up by
1107  // it, then we could leak memory allocated from the preceding
1108  // new expressions. Whether that could happen is not documented
1109  // by guile, but because (a) it is so improbable, and (b) once
1110  // we are in out-of-memory land we are already in severe trouble
1111  // and glib is likely to terminate the program at some point
1112  // anyway, it is not worth troubling ourselves over.
1113  scm_dynwind_unwind_handler(&cgu_delete_vector, args, scm_t_wind_flags(0));
1114  // convert the list to a guile vector so we can access its items
1115  // efficiently in a for loop. This conversion is reasonably
1116  // efficient, in the sense that an ordinary guile vector is an
1117  // array of pointers, pointing to the same scheme objects that the
1118  // list refers to
1119  SCM guile_vec = scm_vector(scm);
1120 
1121  // std::vector::size_type is the same as size_t with the standard
1122  // allocators (but if we were to get a silent narrowing conversion
1123  // on calling std::vector::reserve() below, that doesn't matter -
1124  // instead if 'length' is less than SIZE_MAX but greater than the
1125  // maximum value of std::vector::size_type, at some point a call
1126  // to std::vector::push_back() below would throw and be caught,
1127  // and this function would end up rethrowing it as std::bad_alloc.
1128  // If in a particular implementation SIZE_MAX exceeds
1129  // std::vector::max_size(), a std::length_error exception would be
1130  // thrown by reserve() where max_size() is exceeded. On all
1131  // common implementations, max_size() is equal to SIZE_MAX, but
1132  // were such an exception to arise it would be swallowed (see
1133  // below) and then rethrown by this function as std::bad_alloc.
1134  // If 'length' is greater than SIZE_MAX, a guile out-of-range
1135  // exception would be thrown by scm_to_size_t() which would be
1136  // rethrown by Cgu:Extension::exec() or
1137  // Cgu::Exception::exec_shared as a Cgu::Extension::WrapperError
1138  // C++ exception. This is nice to know but in practice such large
1139  // lists would be unusably slow and a memory exception would be
1140  // reached long before std::vector::max_size() or SIZE_MAX are
1141  // exceeded.
1142  size_t length = scm_to_size_t(scm_vector_length(guile_vec));
1143  try {
1144  res->reserve(length);
1145  }
1146  catch (...) {
1147  badalloc = true;
1148  }
1149  for (size_t count = 0;
1150  count < length && !rv_error && !badalloc;
1151  ++count) {
1152  SCM item = scm_vector_ref(guile_vec, scm_from_size_t(count));
1153  if (scm_is_false(scm_real_p(item)))
1154  rv_error = u8"scheme code did not evaluate to a homogeneous list of real numbers\n";
1155  else {
1156  SCM min = scm_from_double(std::numeric_limits<double>::lowest());
1157  SCM max = scm_from_double(std::numeric_limits<double>::max());
1158  if (scm_is_false(scm_leq_p(item, max)) || scm_is_false(scm_geq_p(item, min)))
1159  rv_error = u8"scheme code evaluated out of range for double\n";
1160  else {
1161  try {
1162  res->push_back(scm_to_double(item));
1163  }
1164  catch (...) {
1165  badalloc = true;
1166  }
1167  }
1168  }
1169  }
1170  }
1171  // all done - no more guile exceptions are possible in this function
1172  // after this so end the dynamic context, take control of the memory
1173  // by RAII and if necessary throw a C++ exception
1174  scm_dynwind_end();
1175  std::unique_ptr<std::vector<double>> up_res(res);
1176  std::unique_ptr<VectorDeleteArgs> up_args(args);
1177  if (badalloc) throw std::bad_alloc();
1178  if (rv_error) throw ReturnValueError(rv_error);
1179  // neither gcc-4.9 nor clang-3.4 will optimize with RVO or move
1180  // semantics here, so force it by hand
1181  return std::move(*res);
1182 }
1183 
1184 /**
1185  * A translator function which can be passed to the third argument of
1186  * Extension::exec() or Extension::exec_shared(). It converts from a
1187  * homogeneous scheme list of strings to a C++ representation of
1188  * std::vector<std::string>. It is thread safe, but see the comments
1189  * above about the thread safety of Extension::exec() and
1190  * Extension::exec_shared().
1191  *
1192  * The returned strings will be in UTF-8 encoding.
1193  *
1194  * Note that the first string in the returned list must not be
1195  * "***cgu-guile-exception***": that string is reserved to the
1196  * implementation.
1197  *
1198  * @param scm An opaque guile SCM object representing the value to
1199  * which the extension file passed to Extension::exec() or
1200  * Extension::exec_shared() evaluated, where that value is a
1201  * homogeneous list of strings.
1202  * @return The std::vector<std::string> representation.
1203  * @exception std::bad_alloc This function might throw std::bad_alloc
1204  * if memory is exhausted and the system throws in that case, or if
1205  * the length of the input list exceeds std::vector::max_size().
1206  * @exception Cgu::Extension::GuileException This exception will be
1207  * thrown if the scheme code in the extension file passed to
1208  * Extension::exec() or Extension::exec_shared() caused a guile
1209  * exception to be thrown. Cgu::Extension::GuileException::what()
1210  * will give particulars of the guile exception thrown, in UTF-8
1211  * encoding.
1212  * @exception Cgu::Extension::ReturnValueError This exception will be
1213  * thrown if the scheme code in the extension file passed to
1214  * Extension::exec() or Extension::exec_shared() does not evaluate to
1215  * the type expected by the translator.
1216  * Cgu::Extension::ReturnValueError::what() will give further
1217  * particulars, in UTF-8 encoding.
1218  * @note No native guile exception will arise in this function and so
1219  * cause guile to jump out of it unless a guile out-of-memory
1220  * condition occurs (given that this function is called after a guile
1221  * extension task has completed, such a condition is very improbable)
1222  * or the length of the input list exceeds SIZE_MAX (the maximum value
1223  * of std::size_t). If such an exception were to arise, the
1224  * implementation would handle it and a C++ exception would be
1225  * generated in its place in Extension::exec() or
1226  * Extension::exec_shared().
1227  *
1228  * Since 2.0.22 and 2.2.5
1229  */
1230 inline std::vector<std::string> list_to_vector_string(SCM scm) {
1232  if (scm_is_false(scm_list_p(scm)))
1233  throw ReturnValueError(u8"scheme code did not evaluate to a list\n");
1234 
1235  // nothing in this function should throw a guile exception unless
1236  // there is a guile out-of-memory exception (which is extremely
1237  // improbable). However, let's cover ourselves in case.
1238  scm_dynwind_begin(scm_t_dynwind_flags(0));
1239  // we cannot have a std::vector object in a scope where a guile
1240  // exception might be raised because it has a non-trivial
1241  // destructor, nor can we use RAII. Instead allocate on free store
1242  // and manage the memory by hand until we can no longer jump on a
1243  // guile exception. In addition we cannot store a C++ exception
1244  // using std::exception_ptr because std::exception_ptr is not
1245  // trivially destructible.
1246  bool badalloc = false;
1247  const char* rv_error = 0;
1248  std::vector<std::string>* res = 0;
1249  VectorDeleteArgs* args = 0;
1250  try {
1251  // it doesn't matter if the second allocation fails, as we clean
1252  // up at the end if there is no guile exception, and if both
1253  // allocations succeed and there were to be a subsequent guile
1254  // exception, cgu_delete_vector cleans up
1255  res = new std::vector<std::string>;
1256  // allocate 'args' on free store, because the continuation in
1257  // which it executes will be up the stack
1258  args = new VectorDeleteArgs{String, res};
1259  }
1260  catch (...) {
1261  badalloc = true;
1262  }
1263  if (!badalloc) {
1264  // there may be a weakness in guile's implementation here: if
1265  // calling scm_dynwind_unwind_handler() were to give rise to a
1266  // guile out-of-memory exception before the handler is set up by
1267  // it, then we could leak memory allocated from the preceding new
1268  // expressions. Whether that could happen is not documented by
1269  // guile, but because (a) it is so improbable, and (b) once we are
1270  // in out-of-memory land we are already in severe trouble and glib
1271  // is likely to terminate the program at some point anyway, it is
1272  // not worth troubling ourselves over.
1273  scm_dynwind_unwind_handler(&cgu_delete_vector, args, scm_t_wind_flags(0));
1274  // convert the list to a guile vector so we can access its items
1275  // efficiently in a for loop. This conversion is reasonably
1276  // efficient, in the sense that an ordinary guile vector is an
1277  // array of pointers, pointing to the same scheme objects that the
1278  // list refers to
1279  SCM guile_vec = scm_vector(scm);
1280 
1281  // std::vector::size_type is the same as size_t with the standard
1282  // allocators (but if we were to get a silent narrowing conversion
1283  // on calling std::vector::reserve() below, that doesn't matter -
1284  // instead if 'length' is less than SIZE_MAX but greater than the
1285  // maximum value of std::vector::size_type, at some point a call
1286  // to std::vector::emplace_back() below would throw and be caught,
1287  // and this function would end up rethrowing it as std::bad_alloc.
1288  // If in a particular implementation SIZE_MAX exceeds
1289  // std::vector::max_size(), a std::length_error exception would be
1290  // thrown by reserve() where max_size() is exceeded. On all
1291  // common implementations, max_size() is equal to SIZE_MAX, but
1292  // were such an exception to arise it would be swallowed (see
1293  // below) and then rethrown by this function as std::bad_alloc.
1294  // If 'length' is greater than SIZE_MAX, a guile out-of-range
1295  // exception would be thrown by scm_to_size_t() which would be
1296  // rethrown by Cgu:Extension::exec() or
1297  // Cgu::Exception::exec_shared as a Cgu::Extension::WrapperError
1298  // C++ exception. This is nice to know but in practice such large
1299  // lists would be unusably slow and a memory exception would be
1300  // reached long before std::vector::max_size() or SIZE_MAX are
1301  // exceeded.
1302  size_t length = scm_to_size_t(scm_vector_length(guile_vec));
1303  try {
1304  res->reserve(length);
1305  }
1306  catch (...) {
1307  badalloc = true;
1308  }
1309  for (size_t count = 0;
1310  count < length && !rv_error && !badalloc;
1311  ++count) {
1312  SCM item = scm_vector_ref(guile_vec, scm_from_size_t(count));
1313  if (scm_is_false(scm_string_p(item)))
1314  rv_error = u8"scheme code did not evaluate to a homogeneous list of string\n";
1315  else {
1316  size_t len;
1317  // we don't need a dynwind handler for 'str' because nothing
1318  // after the call to scm_to_utf8_stringn() and before the call
1319  // to free() can cause a guile exception to be raised
1320  char* str = scm_to_utf8_stringn(item, &len);
1321  try {
1322  res->emplace_back(str, len);
1323  }
1324  catch (...) {
1325  badalloc = true;
1326  }
1327  free(str);
1328  }
1329  }
1330  }
1331  // all done - no more guile exceptions are possible in this function
1332  // after this so end the dynamic context, take control of the memory
1333  // by RAII and if necessary throw a C++ exception
1334  scm_dynwind_end();
1335  std::unique_ptr<std::vector<std::string>> up_res(res);
1336  std::unique_ptr<VectorDeleteArgs> up_args(args);
1337  if (badalloc) throw std::bad_alloc();
1338  if (rv_error) throw ReturnValueError(rv_error);
1339  // neither gcc-4.9 nor clang-3.4 will optimize with RVO or move
1340  // semantics here, so force it by hand
1341  return std::move(*res);
1342 }
1343 
1344 /**
1345  * A translator function which can be passed to the third argument of
1346  * Extension::exec() or Extension::exec_shared(). It converts from a
1347  * scheme integer to a C++ representation of long. It is thread safe,
1348  * but see the comments above about the thread safety of
1349  * Extension::exec() and Extension::exec_shared().
1350  *
1351  * @param scm An opaque guile SCM object representing the value to
1352  * which the extension file passed to Extension::exec() or
1353  * Extension::exec_shared() evaluated, where that value is an integer.
1354  * @return The C++ long representation.
1355  * @exception std::bad_alloc This function might throw std::bad_alloc
1356  * if memory is exhausted and the system throws in that case.
1357  * @exception Cgu::Extension::GuileException This exception will be
1358  * thrown if the scheme code in the extension file passed to
1359  * Extension::exec() or Extension::exec_shared() caused a guile
1360  * exception to be thrown. Cgu::Extension::GuileException::what()
1361  * will give particulars of the guile exception thrown, in UTF-8
1362  * encoding.
1363  * @exception Cgu::Extension::ReturnValueError This exception will be
1364  * thrown if the scheme code in the extension file passed to
1365  * Extension::exec() or Extension::exec_shared() does not evaluate to
1366  * the type expected by the translator, or it is out of range for a
1367  * long. Cgu::Extension::ReturnValueError::what() will give further
1368  * particulars, in UTF-8 encoding.
1369  * @note No native guile exception will arise in this function and so
1370  * cause guile to jump out of it if no guile out-of-memory condition
1371  * occurs (given that this function is called after a guile extension
1372  * task has completed, such a condition is very improbable). If such
1373  * an exception were to arise, the implementation would handle it and
1374  * a C++ exception would be generated in its place in
1375  * Extension::exec() or Extension::exec_shared().
1376  *
1377  * Since 2.0.22 and 2.2.5
1378  */
1379 inline long integer_to_long(SCM scm) {
1381  if (scm_is_false(scm_integer_p(scm)))
1382  throw ReturnValueError(u8"scheme code did not evaluate to an integer\n");
1383  SCM min = scm_from_long(std::numeric_limits<long>::min());
1384  SCM max = scm_from_long(std::numeric_limits<long>::max());
1385  if (scm_is_false(scm_leq_p(scm, max)) || scm_is_false(scm_geq_p(scm, min)))
1386  throw ReturnValueError(u8"scheme code evaluated out of range for long\n");
1387  return scm_to_long(scm);
1388 }
1389 
1390 /**
1391  * A translator function which can be passed to the third argument of
1392  * Extension::exec() or Extension::exec_shared(). It converts from a
1393  * scheme real number to a C++ representation of double. It is thread
1394  * safe, but see the comments above about the thread safety of
1395  * Extension::exec() and Extension::exec_shared().
1396  *
1397  * @param scm An opaque guile SCM object representing the value to
1398  * which the extension file passed to Extension::exec() or
1399  * Extension::exec_shared() evaluated, where that value is a real
1400  * number.
1401  * @return The C++ double representation.
1402  * @exception std::bad_alloc This function might throw std::bad_alloc
1403  * if memory is exhausted and the system throws in that case.
1404  * @exception Cgu::Extension::GuileException This exception will be
1405  * thrown if the scheme code in the extension file passed to
1406  * Extension::exec() or Extension::exec_shared() caused a guile
1407  * exception to be thrown. Cgu::Extension::GuileException::what()
1408  * will give particulars of the guile exception thrown, in UTF-8
1409  * encoding.
1410  * @exception Cgu::Extension::ReturnValueError This exception will be
1411  * thrown if the scheme code in the extension file passed to
1412  * Extension::exec() or Extension::exec_shared() does not evaluate to
1413  * the type expected by the translator, or it is out of range for a
1414  * double. Cgu::Extension::ReturnValueError::what() will give further
1415  * particulars, in UTF-8 encoding.
1416  * @note 1. Prior to versions 2.0.25 and 2.2.8, this translator had a
1417  * bug which caused an out-of-range Cgu::Extension::ReturnValueError
1418  * to be thrown if the scheme code in the extension file evaluated to
1419  * 0.0 or a negative number. This was fixed in versions 2.0.25 and
1420  * 2.2.8.
1421  * @note 2. No native guile exception will arise in this function and
1422  * so cause guile to jump out of it if no guile out-of-memory
1423  * condition occurs (given that this function is called after a guile
1424  * extension task has completed, such a condition is very improbable).
1425  * If such an exception were to arise, the implementation would handle
1426  * it and a C++ exception would be generated in its place in
1427  * Extension::exec() or Extension::exec_shared().
1428  *
1429  * Since 2.0.22 and 2.2.5
1430  */
1431 inline double real_to_double(SCM scm) {
1433  if (scm_is_false(scm_real_p(scm)))
1434  throw ReturnValueError(u8"scheme code did not evaluate to a real number\n");
1435  SCM min = scm_from_double(std::numeric_limits<double>::lowest());
1436  SCM max = scm_from_double(std::numeric_limits<double>::max());
1437  if (scm_is_false(scm_leq_p(scm, max)) || scm_is_false(scm_geq_p(scm, min)))
1438  throw ReturnValueError(u8"scheme code evaluated out of range for double\n");
1439  return scm_to_double(scm);
1440 }
1441 
1442 /**
1443  * A translator function which can be passed to the third argument of
1444  * Extension::exec() or Extension::exec_shared(). It converts from a
1445  * scheme string to a C++ representation of std::string. It is thread
1446  * safe, but see the comments above about the thread safety of
1447  * Extension::exec() and Extension::exec_shared().
1448  *
1449  * The returned string will be in UTF-8 encoding.
1450  *
1451  * @param scm An opaque guile SCM object representing the value to
1452  * which the extension file passed to Extension::exec() or
1453  * Extension::exec_shared() evaluated, where that value is a string.
1454  * @return The std::string representation.
1455  * @exception std::bad_alloc This function might throw std::bad_alloc
1456  * if memory is exhausted and the system throws in that case.
1457  * @exception Cgu::Extension::GuileException This exception will be
1458  * thrown if the scheme code in the extension file passed to
1459  * Extension::exec() or Extension::exec_shared() caused a guile
1460  * exception to be thrown. Cgu::Extension::GuileException::what()
1461  * will give particulars of the guile exception thrown, in UTF-8
1462  * encoding.
1463  * @exception Cgu::Extension::ReturnValueError This exception will be
1464  * thrown if the scheme code in the extension file passed to
1465  * Extension::exec() or Extension::exec_shared() does not evaluate to
1466  * the type expected by the translator.
1467  * Cgu::Extension::ReturnValueError::what() will give further
1468  * particulars, in UTF-8 encoding.
1469  * @note No native guile exception will arise in this function and so
1470  * cause guile to jump out of it if no guile out-of-memory condition
1471  * occurs (given that this function is called after a guile extension
1472  * task has completed, such a condition is very improbable). If such
1473  * an exception were to arise, the implementation would handle it and
1474  * a C++ exception would be generated in its place in
1475  * Extension::exec() or Extension::exec_shared().
1476  *
1477  * Since 2.0.22 and 2.2.5
1478  */
1479 inline std::string string_to_string(SCM scm) {
1481  if (scm_is_false(scm_string_p(scm)))
1482  throw ReturnValueError(u8"scheme code did not evaluate to a string\n");
1483  size_t len;
1484  // it is safe to use unique_ptr here. If scm_to_utf8_stringn()
1485  // succeeds then nothing after it in this function can cause a guile
1486  // exception.
1487  std::unique_ptr<const char, Cgu::CFree> s(scm_to_utf8_stringn(scm, &len));
1488  return std::string(s.get(), len);
1489 }
1490 
1491 /**
1492  * A translator function which can be passed to the third argument of
1493  * Extension::exec() or Extension::exec_shared(). It disregards the
1494  * scheme value passed to it except to trap any guile exception thrown
1495  * by the scheme task and rethrow it as a C++ exception, and returns a
1496  * NULL void* object. It is thread safe, but see the comments above
1497  * about the thread safety of Extension::exec() and
1498  * Extension::exec_shared().
1499  *
1500  * It is mainly intended for use where the scheme script is executed
1501  * for its side effects, perhaps for I/O, and any communication
1502  * necessary is done by guile exceptions.
1503  *
1504  * @param scm An opaque guile SCM object representing the value to
1505  * which the extension file passed to Extension::exec() or
1506  * Extension::exec_shared() evaluated, which is ignored.
1507  * @return A NULL void* object.
1508  * @exception std::bad_alloc This function might throw std::bad_alloc
1509  * if memory is exhausted and the system throws in that case.
1510  * @exception Cgu::Extension::GuileException This exception will be
1511  * thrown if the scheme code in the extension file passed to
1512  * Extension::exec() or Extension::exec_shared() caused a guile
1513  * exception to be thrown. Cgu::Extension::GuileException::what()
1514  * will give particulars of the guile exception thrown, in UTF-8
1515  * encoding.
1516  * @note No native guile exception will arise in this function and so
1517  * cause guile to jump out of it if no guile out-of-memory condition
1518  * occurs (given that this function is called after a guile extension
1519  * task has completed, such a condition is very improbable). If such
1520  * an exception were to arise, the implementation would handle it and
1521  * a C++ exception would be generated in its place in
1522  * Extension::exec() or Extension::exec_shared().
1523  *
1524  * Since 2.0.22 and 2.2.5
1525  */
1526 inline void* any_to_void(SCM scm) {
1528  return 0;
1529 }
1530 
1531 /**
1532  * This function executes scheme code on the guile VM within a C++
1533  * program using this library. See the introductory remarks above for
1534  * its potential uses, about the thread safety of this function, and
1535  * about the use of the TaskManager::exec_shared() as an alternative.
1536  *
1537  * The first argument to this function is a preamble, which can be
1538  * used to pass top level definitions to the scheme code (in other
1539  * words, for argument passing). It's second argument is the filename
1540  * (with path) of the file containing the scheme code to be executed.
1541  * It's third argument is a translator, which will convert the value
1542  * to which the scheme code evaluates (in C++ terms, its return value)
1543  * to a suitable C++ representation. Preformed translators are
1544  * provided by this library to translate from scheme's integers, real
1545  * numbers and strings to C++ longs, doubles and strings respectively,
1546  * and from any uniform lists of these to C++ vectors of the
1547  * corresponding type. There is also a translator for void return
1548  * types. See the introductory remarks above for more information
1549  * about translators.
1550  *
1551  * Any native guile exceptions thrown by the code executed by this
1552  * function (and by any code which it calls) are converted and
1553  * rethrown as C++ exceptions.
1554  *
1555  * The scheme file can call other scheme code, and load modules, in
1556  * the ordinary way. Thus, this function can execute any scheme code
1557  * which guile can execute as a program, and the programmer can (if
1558  * wanted) act on its return value in the C++ code which invokes it.
1559  *
1560  * Thread cancellation is blocked for the thread in which this
1561  * function executes until this function returns.
1562  *
1563  * @param preamble Scheme code such as top level definitions to be
1564  * seen by the code in the file to be executed. This is mainly
1565  * intended for argument passing, but can comprise any valid scheme
1566  * code. It can also be empty (you can pass ""). Any string literals
1567  * must be in UTF-8 encoding.
1568  * @param file The file which is to be executed on the guile VM. This
1569  * should include the full pathname or a pathname relative to the
1570  * current directory. The contents of the file, and in particular any
1571  * string literals in it, must be in UTF-8 encoding. The filename and
1572  * path must also be given in UTF-8 encoding, even if the local
1573  * filename encoding is something different: guile will convert the
1574  * UTF-8 name which it is given to its own internal string encoding
1575  * using unicode code points, and then convert that to locale encoding
1576  * on looking up the filename. However sticking to ASCII for
1577  * filenames and paths (which is always valid UTF-8) will maximise
1578  * portability. The file name can be empty (you can pass ""), in
1579  * which case only the preamble will be evaluated (but for efficiency
1580  * reasons any complex code not at the top level should be included in
1581  * the file rather than in the preamble).
1582  * @param translator The function or callable object which will
1583  * convert the value to which the scheme code evaluates to a C++
1584  * representation which will be returned by this function. The
1585  * translator should take a single argument comprising an opaque guile
1586  * object of type SCM, and return the C++ representation for it.
1587  * @return The C++ representation returned by the translator.
1588  * @exception std::bad_alloc This function might throw std::bad_alloc
1589  * if memory is exhausted and the system throws in that case.
1590  * @exception Cgu::Extension::GuileException This exception will be
1591  * thrown if the scheme code in 'file' (or called by it) throws a
1592  * guile exception. Cgu::Extension::GuileException::what() will give
1593  * particulars of the guile exception thrown, in UTF-8 encoding.
1594  * @exception Cgu::Extension::ReturnValueError This exception will be
1595  * thrown if the code in 'file' does not evaluate to the type expected
1596  * by the translator. Cgu::Extension::ReturnValueError::what() will
1597  * give further particulars, in UTF-8 encoding.
1598  * @exception Cgu::Extension::WrapperError This exception will be
1599  * thrown if a custom translator throws a native guile exception or a
1600  * C++ exception not comprising Extension::GuileException or
1601  * Extension::ReturnValueError, one of the preformed translators
1602  * throws std::bad_alloc or encounters a guile out-of-memory
1603  * exception, one of the preformed list translators encounters an
1604  * input list exceeding SIZE_MAX in length, assigning to an internal
1605  * exception description string throws std::bad_alloc, or evaluation
1606  * of the preamble throws a native guile exception.
1607  *
1608  * Since 2.0.22 and 2.2.5
1609  */
1610 template <class Translator>
1611 auto exec(const std::string& preamble,
1612  const std::string& file,
1613  Translator&& translator) -> typename std::result_of<Translator(SCM)>::type {
1614  // exec_impl() will fail to compile if Ret is a reference type: that
1615  // is a feature, not a bug, as there is no good reason for a
1616  // translator ever to return a reference
1617  typedef typename std::result_of<Translator(SCM)>::type Ret;
1618  return exec_impl<Ret>(preamble, file, std::forward<Translator>(translator), false);
1619 }
1620 
1621 /**
1622  * This function executes scheme code on the guile VM within a C++
1623  * program using this library. See the introductory remarks above for
1624  * its potential uses, about the thread safety of this function, and
1625  * about the use of the TaskManager::exec() as an alternative.
1626  *
1627  * The first argument to this function is a preamble, which can be
1628  * used to pass top level definitions to the scheme code (in other
1629  * words, for argument passing). It's second argument is the filename
1630  * (with path) of the file containing the scheme code to be executed.
1631  * It's third argument is a translator, which will convert the value
1632  * to which the scheme code evaluates (in C++ terms, its return value)
1633  * to a suitable C++ representation. Preformed translators are
1634  * provided by this library to translate from scheme's integers, real
1635  * numbers and strings to C++ longs, doubles and strings respectively,
1636  * and from any uniform lists of these to C++ vectors of the
1637  * corresponding type. There is also a translator for void return
1638  * types. See the introductory remarks above for more information
1639  * about translators.
1640  *
1641  * Any native guile exceptions thrown by the code executed by this
1642  * function (and by any code which it calls) are converted and
1643  * rethrown as C++ exceptions.
1644  *
1645  * The scheme file can call other scheme code, and load modules, in
1646  * the ordinary way. Thus, this function can execute any scheme code
1647  * which guile can execute as a program, and the programmer can (if
1648  * wanted) act on its return value in the C++ code which invokes it.
1649  *
1650  * Thread cancellation is blocked for the thread in which this
1651  * function executes until this function returns.
1652  *
1653  * @param preamble Scheme code such as top level definitions to be
1654  * seen by the code in the file to be executed. This is mainly
1655  * intended for argument passing, but can comprise any valid scheme
1656  * code. It can also be empty (you can pass ""). Any string literals
1657  * must be in UTF-8 encoding.
1658  * @param file The file which is to be executed on the guile VM. This
1659  * should include the full pathname or a pathname relative to the
1660  * current directory. The contents of the file, and in particular any
1661  * string literals in it, must be in UTF-8 encoding. The filename and
1662  * path must also be given in UTF-8 encoding, even if the local
1663  * filename encoding is something different: guile will convert the
1664  * UTF-8 name which it is given to its own internal string encoding
1665  * using unicode code points, and then convert that to locale encoding
1666  * on looking up the filename. However sticking to ASCII for
1667  * filenames and paths (which is always valid UTF-8) will maximise
1668  * portability. The file name can be empty (you can pass ""), in
1669  * which case only the preamble will be evaluated.
1670  * @param translator The function or callable object which will
1671  * convert the value to which the scheme code evaluates to a C++
1672  * representation which will be returned by this function. The
1673  * translator should take a single argument comprising an opaque guile
1674  * object of type SCM, and return the C++ representation for it.
1675  * @return The C++ representation returned by the translator.
1676  * @exception std::bad_alloc This function might throw std::bad_alloc
1677  * if memory is exhausted and the system throws in that case.
1678  * @exception Cgu::Extension::GuileException This exception will be
1679  * thrown if the scheme code in 'file' (or called by it) throws a
1680  * guile exception. Cgu::Extension::GuileException::what() will give
1681  * particulars of the guile exception thrown, in UTF-8 encoding.
1682  * @exception Cgu::Extension::ReturnValueError This exception will be
1683  * thrown if the code in 'file' does not evaluate to the type expected
1684  * by the translator. Cgu::Extension::ReturnValueError::what() will
1685  * give further particulars, in UTF-8 encoding.
1686  * @exception Cgu::Extension::WrapperError This exception will be
1687  * thrown if a custom translator throws a native guile exception or a
1688  * C++ exception not comprising Extension::GuileException or
1689  * Extension::ReturnValueError, one of the preformed translators
1690  * throws std::bad_alloc or encounters a guile out-of-memory
1691  * exception, one of the preformed list translators encounters an
1692  * input list exceeding SIZE_MAX in length, assigning to an internal
1693  * exception description string throws std::bad_alloc, or evaluation
1694  * of the preamble throws a native guile exception.
1695  *
1696  * Since 2.0.24 and 2.2.7
1697  */
1698 template <class Translator>
1699 auto exec_shared(const std::string& preamble,
1700  const std::string& file,
1701  Translator&& translator) -> typename std::result_of<Translator(SCM)>::type {
1702  // exec_impl() will fail to compile if Ret is a reference type: that
1703  // is a feature, not a bug, as there is no good reason for a
1704  // translator ever to return a reference
1705  typedef typename std::result_of<Translator(SCM)>::type Ret;
1706  return exec_impl<Ret>(preamble, file, std::forward<Translator>(translator), true);
1707 }
1708 
1709 } // namespace Extension
1710 
1711 } // namespace Cgu
1712 
1713 #endif // CGU_EXTENSION_H
std::vector< long > list_to_vector_long(SCM scm)
Definition: extension.h:911
GuileException(const char *msg)
Definition: extension.h:504
long integer_to_long(SCM scm)
Definition: extension.h:1379
~ReturnValueError()
Definition: extension.h:519
T get() const noexcept
Definition: shared_handle.h:762
~GuileException()
Definition: extension.h:507
const char * err_text() const
Definition: extension.h:515
void * any_to_void(SCM scm)
Definition: extension.h:1526
WrapperError(const char *msg)
Definition: extension.h:526
This file provides classes for type erasure.
Definition: extension.h:510
SCM exception_to_string(SCM key, SCM args) noexcept
Definition: extension.h:742
A class enabling the cancellation state of a thread to be controlled.
Definition: thread.h:718
double real_to_double(SCM scm)
Definition: extension.h:1431
Definition: extension.h:498
std::string string_to_string(SCM scm)
Definition: extension.h:1479
std::vector< double > list_to_vector_double(SCM scm)
Definition: extension.h:1070
virtual const char * what() const
Definition: extension.h:525
auto exec(const std::string &preamble, const std::string &file, Translator &&translator) -> typename std::result_of< Translator(SCM)>::type
Definition: extension.h:1611
A wrapper class for pthread mutexes.
Definition: mutex.h:117
Provides wrapper classes for pthread mutexes and condition variables, and scoped locking classes for ...
Definition: application.h:44
std::vector< std::string > list_to_vector_string(SCM scm)
Definition: extension.h:1230
Definition: extension.h:522
virtual const char * what() const
Definition: extension.h:514
~WrapperError()
Definition: extension.h:528
virtual const char * what() const
Definition: extension.h:502
auto exec_shared(const std::string &preamble, const std::string &file, Translator &&translator) -> typename std::result_of< Translator(SCM)>::type
Definition: extension.h:1699
void rethrow_guile_exception(SCM scm)
Definition: extension.h:828
ReturnValueError(const char *msg)
Definition: extension.h:516
The callback interface class.
Definition: callback.h:567
const char * guile_text() const
Definition: extension.h:503