c++-gtk-utils
extension.h
Go to the documentation of this file.
1 /* Copyright (C) 2014 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(), it is trivial to do (see the example
76  * 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 included in
200  * the preamble of a task, or imported by guile's 'use-modules' or
201  * 'load' procedures in the task, from the top level definitions of
202  * other tasks started by calls to Extension::exec(), by calling
203  * 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 both the 'make-fresh-user-module'
215  * and 'load' procedures leak small amounts of memory. If a
216  * particular program is likely to call Extension::exec() more than
217  * about 5,000 or 10,000 times, it would be better to use
218  * 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 import clashing definitions using 'use-modules' or 'load'. The
230  * need for Extension::exec_shared() to be called only in one thread
231  * in the example above was the reason why the TaskManager object in
232  * that example was set to have a maximum thread count of 1. In
233  * effect the TaskManager object was a dedicated serial dispatcher for
234  * all scheme tasks.
235  *
236  * The calling by Extension::exec_shared() of 'primitive-load' instead
237  * of 'load' may have some small effect on efficiency. It it best for
238  * the file passed to that function to hand off any complex code to
239  * modules prepared using guile's modules interface (which will be
240  * compiled into bytecode), and which are then loaded using
241  * 'use-modules' the first time Extension::exec_shared() is called, or
242  * by having the first call to Extension::exec_shared() (and only the
243  * first call) import any needed files into the top level using
244  * 'load'.
245  *
246  * Note that some guile global state may be shared between tasks
247  * whether Extension::exec() or Extension::exec_shared() is used. For
248  * example, if the guile 'add-to-load-path' procedure is called to add
249  * a local directory to the search path used by 'use-modules' or
250  * 'load', that will have effect for all other tasks.
251  *
252  * Other thread safety points
253  * --------------------------
254  *
255  * Leaving aside what has been said above, there are a few other
256  * issues to keep in mind if executing scheme code in more than one
257  * thread.
258  *
259  * First, the initialization of guile < 2.0.10 is not thread safe.
260  * One thread needs to have called Extension::exec() or
261  * Extension::exec_shared() once and returned before any other threads
262  * call the function. This can be achieved by the simple expedient of
263  * executing the statement:
264  *
265  * @code
266  * Extension::exec_shared("", "", &Extension::any_to_void);
267  * @endcode
268  *
269  * and waiting for it to return before any tasks are added to a
270  * TaskManager object running more than one thread. This issue is
271  * fixed in guile-2.0.10. However there is a further snag. Certain
272  * aspects of guile module loading are not thread safe. One way
273  * around this is to load all the modules that tasks may use in
274  * advance, by loading the modules in the preamble of the above
275  * statement (or to have that statement execute a file which loads the
276  * modules). If that is done, it should be fine afterwards to run
277  * Extension::exec() on a TaskManager object running any number of
278  * threads, or on a Thread::Future object or std::async() task.
279  * (However, note that if using Extension::exec() the modules would
280  * need to be reloaded in each task in order to make them visible to
281  * the task, but that would be done safely if they have previously
282  * been loaded in another task.)
283  *
284  * This issue is likely to be fixed in a future version of guile.
285  *
286  * If a C++ program is to run guile tasks on a TaskManager object
287  * having a maximum thread count greater than one (or in more than one
288  * thread in some other way), one other point should be noted. When a
289  * scheme file is executed for the first time by a user by being
290  * passed as the second argument of Extension::exec() (or by having
291  * 'load' applied to it in some other way), it will be compiled into
292  * byte code, the byte code will then be cached on the file system for
293  * that and subsequent calls, and the byte code then executed. Bad
294  * things might happen if concurrent calls to Extension::exec(), or to
295  * the 'load' or 'use-modules' procedures, are made in respect of the
296  * same scheme file for the "first" time, if there might be a race as
297  * to which of them is the "first" call in respect of the file: that
298  * is, if it causes two or more threads to try to compile the same
299  * file into byte code concurrently. This is only an issue the first
300  * time a particular user executes a scheme file, and can be avoided
301  * (amongst other ways) by having the C++ program concerned
302  * pre-compile the relevant scheme file before Extension::exec() or
303  * Extension::exec_shared() is first called, by means of the 'guild
304  * compile [filename]' command. The following gives more information
305  * about compilation: <A
306  * HREF="http://www.gnu.org/software/guile/manual/html_node/Compilation.html#Compilation">
307  * Compiling Scheme Code</A>
308  *
309  * Licence
310  * -------
311  *
312  * The c++-gtk-utils library (and this c++-gtk-utils/extension.h
313  * header file) follows glib and GTK+ by being released under the LGPL
314  * version 2.1 or later. libguile is released under the LGPL version
315  * 3 or later. The c++-gtk-utils library object code does not link to
316  * libguile, nor does it incorporate anything in the
317  * c++-gtk-utils/extension.h header. Instead
318  * c++-gtk-utils/extension.h contains all its code as a separate
319  * unlinked header for any program which wants to include it (this is
320  * partly because some of it comprises template functions).
321  *
322  * There are two consequences. If you want to use Extension::exec()
323  * or Extension::exec_shared(), the program which calls it will need
324  * to link itself explicitly with libguile as well as c++-gtk-utils,
325  * and to do that will need to use pkg-config to obtain libguile's
326  * cflags and libs particulars (its pkg-config file is guile-2.0.pc).
327  * This library does NOT do that for you. Secondly, by linking with
328  * libguile you will be governed by the LGPL version 3 or later,
329  * instead of the LGPL version 2.1 or later, with respect to that
330  * linking. That's fine (there is nothing wrong with the LGPL version
331  * 3 and this library permits that) but you should be aware of it.
332  * The scheme code in guile's scheme level modules is also in the main
333  * released under the LGPL version 3 or later ("in the main" because
334  * readline.scm, comprised in the readline module, is released under
335  * the GPL version 3 or later).
336  *
337  * Custom translators
338  * ------------------
339  *
340  * Any function or callable object which translates from an opaque SCM
341  * value to a suitable C++ representation can be passed as the third
342  * argument of Extension::exec() or Extension::exec_shared(). C++
343  * type deduction on template resolution will take care of everything
344  * else. The translator can execute any functions offered by
345  * libguile, because when the translator is run the program is still
346  * in guile mode. The fulsome guile documentation sets out the
347  * libguile functions which are callable in C/C++ code.
348  *
349  * The first call in a custom translator should normally be to the
350  * Extension::rethrow_guile_exception() function. This function tests
351  * whether a guile exception arose in executing the scheme file, and
352  * throws a C++ exception if it did. The preformed translators in
353  * extension.h provide worked examples of how a custom translator
354  * might be written.
355  *
356  * If something done in a custom translator were to raise a guile
357  * exception, the library implementation would handle it and a C++
358  * exception would be generated in its place in Extension::exec() or
359  * Extension::exec_shared(). However, a custom translator should not
360  * allow a guile exception arising from calls to libguile made by it
361  * to exit a C++ scope in which the translator has constructed a local
362  * C++ object which is not trivially destructible: that would give
363  * rise to undefined behaviour, with the likely result that the C++
364  * object's destructor would not be called. One approach to this
365  * (adopted in the preformed translators) is to allocate on free store
366  * all local C++ objects to be constructed in the translator which are
367  * not trivially destructible, and to manage their lifetimes manually
368  * using local C++ try/catch blocks rather than RAII, with dynwind
369  * unwind handlers to release memory were there to be a guile
370  * exception (but note that no C++ exception should transit out of a
371  * scm_dynwind_begin()/scm_dynwind_end() pair). It is also a good
372  * idea to test for any condition which might cause a guile exception
373  * to be raised in the translator in the first place, and throw a C++
374  * exception beforehand. Then the only condition which might cause a
375  * guile exception to occur in the translator is an out-of-memory
376  * condition, which is highly improbable in a translator as the
377  * translator is run after the guile task has completed. Heap
378  * exhaustion in such a case probably spells doom for the program
379  * concerned anyway, if it has other work to do.
380  *
381  * Scheme
382  * ------
383  * If you want to learn more about scheme, these are useful sources:
384  * <P>
385  * <A HREF="http://www.gnu.org/software/guile/manual/html_node/Hello-Scheme_0021.html"> Chapter 3 of the Guile Manual</A>
386  * (the rest of the manual is also good reading).</P>
387  * <P>
388  * <A HREF="http://www.scheme.com/tspl4/">The Scheme Programming Language, 4th edition</A></P>
389  */
390 
391 #include <string>
392 #include <vector>
393 #include <exception>
394 #include <memory> // for std::unique_ptr
395 #include <type_traits> // for std::result_of
396 #include <limits> // for std::numeric_limits
397 #include <utility> // for std::forward and std::move
398 #include <new> // for std::bad_alloc
399 
400 #include <stddef.h> // for size_t
401 #include <stdlib.h> // for free()
402 #include <string.h> // for strlen() and strncmp()
403 
404 #include <glib.h>
405 
407 #include <c++-gtk-utils/callback.h>
408 #include <c++-gtk-utils/thread.h>
410 
411 #include <libguile.h>
412 
413 
414 #ifndef DOXYGEN_PARSING
415 namespace Cgu {
416 
417 namespace Extension {
418 
419 struct FormatArgs {
420  SCM text;
421  SCM rest;
422 };
423 
424 enum VectorDeleteType {Long, Double, String};
425 
426 struct VectorDeleteArgs {
427  VectorDeleteType type;
428  void* vec;
429 };
430 
431 } // namespace Extension
432 
433 } // namespace Cgu
434 
435 namespace {
436 extern "C" {
437  inline SCM cgu_format_try_handler(void* data) {
438  using Cgu::Extension::FormatArgs;
439  FormatArgs* format_args = static_cast<FormatArgs*>(data);
440  return scm_simple_format(SCM_BOOL_F, format_args->text, format_args->rest);
441  }
442  inline SCM cgu_format_catch_handler(void*, SCM, SCM) {
443  return SCM_BOOL_F;
444  }
445  inline void* cgu_guile_wrapper(void* data) {
446  try {
447  static_cast<Cgu::Callback::Callback*>(data)->dispatch();
448  }
449  // an elipsis catch block is fine as thread cancellation is
450  // blocked. We can only enter this block if assigning to one of
451  // the exception strings in the callback has thrown
452  // std::bad_alloc. For that case we return a non-NULL pointer to
453  // indicate error (the 'data' argument is convenient and
454  // guaranteed to be standard-conforming for this).
455  catch (...) {
456  return data;
457  }
458  return 0;
459  }
460  inline void cgu_delete_vector(void* data) {
461  using Cgu::Extension::VectorDeleteArgs;
462  VectorDeleteArgs* args = static_cast<VectorDeleteArgs*>(data);
463  switch (args->type) {
464  case Cgu::Extension::Long:
465  delete static_cast<std::vector<long>*>(args->vec);
466  break;
467  case Cgu::Extension::Double:
468  delete static_cast<std::vector<double>*>(args->vec);
469  break;
470  case Cgu::Extension::String:
471  delete static_cast<std::vector<std::string>*>(args->vec);
472  break;
473  default:
474  g_critical("Incorrect argument passed to cgu_delete_vector");
475  }
476  delete args;
477  }
478 } // extern "C"
479 } // unnamed namespace
480 #endif // DOXYGEN_PARSING
481 
482 namespace Cgu {
483 
484 namespace Extension {
485 
486 class GuileException: public std::exception {
487  Cgu::GcharSharedHandle message;
488  Cgu::GcharSharedHandle guile_message;
489 public:
490  virtual const char* what() const throw() {return (const char*)message.get();}
491  const char* guile_text() const throw() {return (const char*)guile_message.get();}
492  GuileException(const char* msg):
493  message(g_strdup_printf(u8"Cgu::Extension::GuileException: %s", msg)),
494  guile_message(g_strdup(msg)) {}
495  ~GuileException() throw() {}
496 };
497 
498 class ReturnValueError: public std::exception {
499  Cgu::GcharSharedHandle message;
500  Cgu::GcharSharedHandle err_message;
501 public:
502  virtual const char* what() const throw() {return (const char*)message.get();}
503  const char* err_text() const throw() {return (const char*)err_message.get();}
504  ReturnValueError(const char* msg):
505  message(g_strdup_printf(u8"Cgu::Extension::ReturnValueError: %s", msg)),
506  err_message(g_strdup(msg)) {}
507  ~ReturnValueError() throw() {}
508 };
509 
510 class WrapperError: public std::exception {
511  Cgu::GcharSharedHandle message;
512 public:
513  virtual const char* what() const throw() {return (const char*)message.get();}
514  WrapperError(const char* msg):
515  message(g_strdup_printf(u8"Cgu::Extension::WrapperError: %s", msg)) {}
516  ~WrapperError() throw() {}
517 };
518 
519 #ifndef DOXYGEN_PARSING
520 
521 // we might as well take 'translator' by collapsible reference. If it
522 // is handed a rvalue function object, it will be implicitly converted
523 // to lvalue (and if necessary constructed as such) in order to take a
524 // lvalue reference on lambda construction. If it is already a
525 // lvalue, it will be passed through seamlessly.
526 template <class Ret, class Translator>
527 Ret exec_impl(const std::string& preamble,
528  const std::string& file,
529  Translator&& translator,
530  bool shared) {
531 
533 
534  std::string loader;
535  if (!shared)
536  loader += u8"(set-current-module (make-fresh-user-module))";
537  loader += preamble;
538  if (!file.empty()) {
539  if (shared)
540  loader += u8"((lambda ()";
541  loader += u8"(catch "
542  "#t"
543  "(lambda ()"
544  "(";
545  if (shared)
546  loader += u8"primitive-load \"";
547  else
548  loader += u8"load \"";
549  loader += file;
550  loader += u8"\"))"
551  "(lambda (key . details)"
552  "(cons \"***cgu-guile-exception***\" (cons key details))))";
553  if (shared)
554  loader += u8"))";
555  }
556 
557  Ret retval;
558  bool result = false;
559  std::string guile_except;
560  std::string guile_ret_val_err;
561  std::string gen_err;
562 
563  // we construct a Callback::Callback object here to perform type
564  // erasure. Otherwise we would have to pass scm_with_guile() a
565  // function pointer to a function templated on Translator and Ret,
566  // which must have C++ language linkage (§14/4 of C++ standard).
567  // Technically this would give undefined behaviour as
568  // scm_with_guile() expects a function pointer with C language
569  // linkage, although gcc and clang would accept it. The whole of
570  // this callback will be executed in guile mode via
571  // cgu_guile_wrapper(), so it can safely call libguile functions
572  // (provided that a translator does not allow any guile exceptions
573  // to escape a C++ scope with local objects which are not trivially
574  // destructible). It is also safe to pass 'translator', 'retval',
575  // 'loader', 'result' and the exception strings to it by reference,
576  // because scm_with_guile() will block until it has completed
577  // executing. cgu_guile_wrapper() will trap any std::bad_alloc
578  // exception thrown by the string assignments in the catch blocks in
579  // this lambda. This lambda is safe against a jump to an exit from
580  // scm_with_guile() arising from a native guile exception in
581  // translator, because its body has no objects in local scope
582  // requiring destruction.
583  std::unique_ptr<Cgu::Callback::Callback> cb(Cgu::Callback::lambda<>([&] () -> void {
584  SCM scm = scm_eval_string(scm_from_utf8_string(loader.c_str()));
585 
586  // have a dynwind context and async block while translator is
587  // executing. This is to cater for the pathological case of
588  // the scheme script having set up a signal handler which
589  // might throw a guile exception, or having chained a series
590  // of system asyncs which are still queued for action, which
591  // might otherwise cause the translator to trigger a guile
592  // exception while a non-trivially destructible object is in
593  // the local scope of translator. (Highly unlikely, but easy
594  // to deal with.) This is entirely safe as no C++ exception
595  // arising from the translator can transit across the dynamic
596  // context in this function - see below. So we have (i) no
597  // C++ exception can transit across a guile dynamic context,
598  // and (ii) no guile exception can escape out of a local C++
599  // scope by virtue of an async executing (it might still
600  // escape with a non-trivially destructible object in
601  // existence if a custom translator has not been written
602  // correctly, but there is nothing we can do about that).
603  // Note that some guile installations do not link
604  // scm_dynwind_block_asyncs() correctly - this is tested at
605  // configuration time.
606 #ifndef CGU_GUILE_HAS_BROKEN_LINKING
607  scm_dynwind_begin(scm_t_dynwind_flags(0));
608  scm_dynwind_block_asyncs();
609 #endif
610  // we cannot use std::exception_ptr here to store a C++
611  // exception object, because std::exception_ptr is not
612  // trivially destructible and a guile exception in
613  // 'translator' could jump out of this scope to its
614  // continuation in scm_with_guile()
615  bool badalloc = false;
616  try {
617  retval = translator(scm);
618  result = true; // this will detect any guile exception in
619  // the preamble or 'translator' which causes
620  // scm_with_guile() to return prematurely.
621  // We could have done it instead by reversing
622  // the return values of cgu_guile_wrapper
623  // (non-NULL for success and NULL for
624  // failure) because scm_with_guile() returns
625  // NULL if it exits on an uncaught guile
626  // exception, but this approach enables us to
627  // discriminate between a C++ memory
628  // exception in the wrapper and a guile
629  // exception in the preamble or 'translator',
630  // at a minimal cost of one assignment to a
631  // bool.
632  }
633  catch (GuileException& e) {
634  try {
635  guile_except = e.guile_text();
636  }
637  catch (...) {
638  badalloc = true;
639  }
640  }
641  catch (ReturnValueError& e) {
642  try {
643  guile_ret_val_err = e.err_text();
644  }
645  catch (...) {
646  badalloc = true;
647  }
648  }
649  catch (std::exception& e) {
650  try {
651  gen_err = e.what();
652  }
653  catch (...) {
654  badalloc = true;
655  }
656  }
657  catch (...) {
658  try {
659  gen_err = u8"C++ exception thrown in cgu_guile_wrapper()";
660  }
661  catch (...) {
662  badalloc = true;
663  }
664  }
665 #ifndef CGU_GUILE_HAS_BROKEN_LINKING
666  scm_dynwind_end();
667 #endif
668  if (badalloc) throw std::bad_alloc(); // this will be caught in cgu_guile_wrapper()
669  }));
670  // cgu_guile_wrapper(), and so scm_with_guile() will return a
671  // non-NULL value if assigning to one of the exception description
672  // strings above threw std::bad_alloc
673  if (scm_with_guile(&cgu_guile_wrapper, cb.get()))
674  throw WrapperError(u8"cgu_guile_wrapper() has trapped std::bad_alloc");
675  if (!guile_except.empty())
676  throw GuileException(guile_except.c_str());
677  if (!guile_ret_val_err.empty())
678  throw ReturnValueError(guile_ret_val_err.c_str());
679  if (!gen_err.empty())
680  throw WrapperError(gen_err.c_str());
681  if (!result)
682  throw WrapperError(u8"the preamble or translator threw a native guile exception");
683  return retval;
684 }
685 
686 #endif // DOXYGEN_PARSING
687 
688 /**
689  * This function is called by Extension::rethrow_guile_exception()
690  * where the scheme code executed by Extension::exec() or
691  * Extension::exec_shared() has exited with a guile exception. It
692  * converts the raw guile exception information represented by the
693  * 'key' and 'args' arguments of a guile catch handler to a more
694  * readable form. It is made available as part of the public
695  * interface so that any custom translators can also use it if they
696  * choose to provide their own catch expressions. This function does
697  * not throw any C++ exceptions. No native guile exception will arise
698  * in this function and so cause guile to jump out of it assuming no
699  * guile out-of-memory condition occurs (and given that this function
700  * is called after a guile extension task has completed, such a
701  * condition is very improbable). It is thread safe, but see the
702  * comments above about the thread safety of Extension::exec() and
703  * Extension::exec_shared().
704  *
705  * @param key An opaque guile SCM object representing a symbol
706  * comprising the 'key' argument of the exception handler of a guile
707  * catch expression.
708  * @param args An opaque guile SCM object representing a list
709  * comprising the 'args' argument of the exception handler of a guile
710  * catch expression.
711  * @return An opaque guile SCM object representing a guile string.
712  *
713  * Since 2.0.22 and 2.2.5
714  */
715 inline SCM exception_to_string(SCM key, SCM args) noexcept {
716  // The args of most exceptions thrown by guile are in the following format:
717  // (car args) - a string comprising the name of the procedure generating the exception
718  // (cadr args) - a string containing text, possibly with format directives (escape sequences)
719  // (caddr args) - a list containing items matching the format directives, or #f if none
720  // (cadddr args) - (not used here) a list of additional objects (eg the errno for some errors),
721  // or #f if none
722  SCM ret = SCM_BOOL_F;
723  int length = scm_to_int(scm_length(args));
724  if (length) {
725  SCM first = scm_car(args);
726  if (scm_is_true(scm_string_p(first))) {
727  // if a single user string, output it
728  if (length == 1) {
729  ret = scm_string_append(scm_list_4(scm_from_utf8_string(u8"Exception "),
730  scm_symbol_to_string(key),
731  scm_from_utf8_string(u8": "),
732  first));
733  }
734  else { // length > 1
735  SCM second = scm_cadr(args);
736  if (scm_is_true(scm_string_p(second))) {
737  // we should have a standard guile exception string, as above
738  SCM text = scm_string_append(scm_list_n(scm_from_utf8_string(u8"Exception "),
739  scm_symbol_to_string(key),
740  scm_from_utf8_string(u8" in procedure "),
741  first,
742  scm_from_utf8_string(u8": "),
743  second,
744  SCM_UNDEFINED));
745  if (length == 2)
746  ret = text;
747  else { // length > 2
748  SCM third = scm_caddr(args);
749  if (scm_is_false(third))
750  ret = text;
751  else if (scm_is_true(scm_list_p(third))) {
752  FormatArgs format_args = {text, third};
753  ret = scm_internal_catch(SCM_BOOL_T,
754  &cgu_format_try_handler,
755  &format_args,
756  &cgu_format_catch_handler,
757  0);
758  }
759  }
760  }
761  }
762  }
763  }
764  // fall back to generic formatting if first or second elements of
765  // args is not a string or simple-format failed above
766  if (scm_is_false(ret)) {
767  // there is no need for a catch block: we know simple-format
768  // cannot raise an exception here
769  ret = scm_simple_format(SCM_BOOL_F,
770  scm_from_utf8_string(u8"Exception ~S: ~S"),
771  scm_list_2(key, args));
772  }
773  return ret;
774 }
775 
776 /**
777  * This function tests whether a guile exception arose in executing a
778  * scheme extension file, and throws Cgu::Extension::GuileException if
779  * it did. It is intended for use by custom translators, as the first
780  * thing the translator does. It is thread safe, but see the comments
781  * above about the thread safety of Extension::exec() and
782  * Extension::exec_shared().
783  *
784  * @param scm An opaque guile SCM object representing the value to
785  * which the extension file passed to Extension::exec() or
786  * Extension::exec_shared() evaluated.
787  * @exception std::bad_alloc This function might throw std::bad_alloc
788  * if memory is exhausted and the system throws in that case.
789  * @exception Cgu::Extension::GuileException This exception will be
790  * thrown if the scheme code executed in the extension file passed to
791  * Extension::exec() or Extension::exec_shared() threw a guile
792  * exception. Cgu::Extension::GuileException::what() will give
793  * particulars of the guile exception thrown, in UTF-8 encoding.
794  * @note No native guile exception will arise in this function and so
795  * cause guile to jump out of it if no guile out-of-memory condition
796  * occurs (given that this function is called after a guile extension
797  * task has completed, such a condition is very improbable).
798  *
799  * Since 2.0.22 and 2.2.5
800  */
801 inline void rethrow_guile_exception(SCM scm) {
802  // guile exceptions are always presented to this function as a
803  // scheme list
804  if (scm_is_false(scm_list_p(scm))
805  || scm_is_true(scm_null_p(scm))) return;
806  SCM first = scm_car(scm);
807  if (scm_is_true(scm_string_p(first))) {
808  size_t len;
809  const char* text = 0;
810  // nothing in this function should throw a guile exception unless
811  // there is a guile out-of-memory exception (which is extremely
812  // improbable). However, let's cover ourselves in case
813  scm_dynwind_begin(scm_t_dynwind_flags(0));
814  char* car = scm_to_utf8_stringn(first, &len);
815  // there may be a weakness in guile's implementation here: if
816  // calling scm_dynwind_unwind_handler() were to give rise to an
817  // out-of-memory exception before the handler is set up by it,
818  // then we could leak memory allocated from the preceding call to
819  // scm_to_utf8_stringn(). Whether that could happen is not
820  // documented, but because (a) it is so improbable, and (b) once
821  // we are in out-of-memory land we are already in severe trouble
822  // and glib is likely to terminate the program at some point
823  // anyway, it is not worth troubling ourselves over.
824  scm_dynwind_unwind_handler(&free, car, scm_t_wind_flags(0));
825  if (len == strlen(u8"***cgu-guile-exception***")
826  && !strncmp(car, u8"***cgu-guile-exception***", len)) {
827  SCM str = exception_to_string(scm_cadr(scm), scm_cddr(scm));
828  // we don't need a dynwind handler for 'text' because nothing
829  // after the call to scm_to_utf8_stringn() can cause a guile
830  // exception to be raised
831  text = scm_to_utf8_stringn(str, &len);
832  }
833  // all done - no more guile exceptions are possible in this
834  // function after this so end the dynamic context, take control of
835  // the memory by RAII and if necessary throw a C++ exception
836  scm_dynwind_end();
837  std::unique_ptr<char, Cgu::CFree> up_car(car);
838  std::unique_ptr<const char, Cgu::CFree> up_text(text);
839  // if 'text' is not NULL, 'len' contains its length in bytes
840  if (text) throw GuileException(std::string(text, len).c_str());
841  }
842 }
843 
844 /**
845  * A translator function which can be passed to the third argument of
846  * Extension::exec() or Extension::exec_shared(). It converts from a
847  * homogeneous scheme list of integers to a C++ representation of
848  * std::vector<long>. It is thread safe, but see the comments above
849  * about the thread safety of Extension::exec() and
850  * Extension::exec_shared().
851  *
852  * @param scm An opaque guile SCM object representing the value to
853  * which the extension file passed to Extension::exec() or
854  * Extension::exec_shared() evaluated, where that value is a
855  * homogeneous list of integers.
856  * @return The std::vector<long> representation.
857  * @exception std::bad_alloc This function might throw std::bad_alloc
858  * if memory is exhausted and the system throws in that case.
859  * @exception Cgu::Extension::GuileException This exception will be
860  * thrown if the scheme code in the extension file passed to
861  * Extension::exec() or Extension::exec_shared() caused a guile
862  * exception to be thrown. Cgu::Extension::GuileException::what()
863  * will give particulars of the guile exception thrown, in UTF-8
864  * encoding.
865  * @exception Cgu::Extension::ReturnValueError This exception will be
866  * thrown if the scheme code in the extension file passed to
867  * Extension::exec() or Extension::exec_shared() does not evaluate to
868  * the type expected by the translator, or it is out of range for a
869  * long. Cgu::Extension::ReturnValueError::what() will give further
870  * particulars, in UTF-8 encoding.
871  * @note No native guile exception will arise in this function and so
872  * cause guile to jump out of it if no guile out-of-memory condition
873  * occurs (given that this function is called after a guile extension
874  * task has completed, such a condition is very improbable). If such
875  * an exception were to arise, the implementation would handle it and
876  * a C++ exception would be generated in its place in
877  * Extension::exec() or Extension::exec_shared().
878  *
879  * Since 2.0.22 and 2.2.5
880  */
881 inline std::vector<long> list_to_vector_long(SCM scm) {
883  if (scm_is_false(scm_list_p(scm)))
884  throw ReturnValueError(u8"scheme code did not evaluate to a list\n");
885 
886  // nothing in this function should throw a guile exception unless
887  // there is a guile out-of-memory exception (which is extremely
888  // improbable). However, let's cover ourselves in case.
889  scm_dynwind_begin(scm_t_dynwind_flags(0));
890  // we cannot have a std::vector object in a scope where a guile
891  // exception might be raised because it has a non-trivial
892  // destructor, nor can we use RAII. Instead allocate on free store
893  // and manage the memory by hand until we can no longer jump on a
894  // guile exception. In addition we cannot store a C++ exception
895  // using std::exception_ptr because std::exception_ptr is not
896  // trivially destructible.
897  bool badalloc = false;
898  const char* rv_error = 0;
899  std::vector<long>* res = 0;
900  VectorDeleteArgs* args = 0;
901  try {
902  res = new std::vector<long>;
903  }
904  catch (...) {
905  badalloc = true;
906  }
907  if (!badalloc) {
908  // allocate 'args' on free store, because the continuation in
909  // which it executes will be up the stack
910  try {
911  args = new VectorDeleteArgs{Long, res};
912  }
913  catch (...) {
914  badalloc = true;
915  }
916  if (!badalloc) {
917  // there may be a weakness in guile's implementation here: if
918  // calling scm_dynwind_unwind_handler() were to give rise to a
919  // guile out-of-memory exception before the handler is set up by
920  // it, then we could leak memory allocated from the preceding
921  // new expressions. Whether that could happen is not documented
922  // by guile, but because (a) it is so improbable, and (b) once
923  // we are in out-of-memory land we are already in severe trouble
924  // and glib is likely to terminate the program at some point
925  // anyway, it is not worth troubling ourselves over.
926  scm_dynwind_unwind_handler(&cgu_delete_vector, args, scm_t_wind_flags(0));
927  int length = scm_to_int(scm_length(scm));
928  for (int count = 0;
929  count < length && !rv_error && !badalloc;
930  ++count) {
931  SCM item = scm_list_ref(scm, scm_from_int(count));
932  if (scm_is_false(scm_integer_p(item)))
933  rv_error = u8"scheme code did not evaluate to a homogeneous list of integer\n";
934  else {
935  SCM min = scm_from_long(std::numeric_limits<long>::min());
936  SCM max = scm_from_long(std::numeric_limits<long>::max());
937  if (scm_is_false(scm_leq_p(item, max)) || scm_is_false(scm_geq_p(item, min)))
938  rv_error = u8"scheme code evaluated out of range for long\n";
939  else {
940  try {
941  res->push_back(scm_to_long(item));
942  }
943  catch (...) {
944  badalloc = true;
945  }
946  }
947  }
948  }
949  }
950  }
951  // all done - no more guile exceptions are possible in this function
952  // after this so end the dynamic context, take control of the memory
953  // by RAII and if necessary throw a C++ exception
954  scm_dynwind_end();
955  std::unique_ptr<std::vector<long>> up_res(res);
956  std::unique_ptr<VectorDeleteArgs> up_args(args);
957  if (badalloc) throw std::bad_alloc();
958  if (rv_error) throw ReturnValueError(rv_error);
959  // neither gcc-4.9 nor clang-3.4 will optimize with RVO or move
960  // semantics here, so force it by hand
961  return std::move(*res);
962 }
963 
964 /**
965  * A translator function which can be passed to the third argument of
966  * Extension::exec() or Extension::exec_shared(). It converts from a
967  * homogeneous scheme list of real numbers to a C++ representation of
968  * std::vector<double>. It is thread safe, but see the comments above
969  * about the thread safety of Extension::exec() and
970  * Extension::exec_shared().
971  *
972  * @param scm An opaque guile SCM object representing the value to
973  * which the extension file passed to Extension::exec() or
974  * Extension::exec_shared() evaluated, where that value is a
975  * homogeneous list of real numbers.
976  * @return The std::vector<double> representation.
977  * @exception std::bad_alloc This function might throw std::bad_alloc
978  * if memory is exhausted and the system throws in that case.
979  * @exception Cgu::Extension::GuileException This exception will be
980  * thrown if the scheme code in the extension file passed to
981  * Extension::exec() or Extension::exec_shared() caused a guile
982  * exception to be thrown. Cgu::Extension::GuileException::what()
983  * will give particulars of the guile exception thrown, in UTF-8
984  * encoding.
985  * @exception Cgu::Extension::ReturnValueError This exception will be
986  * thrown if the scheme code in the extension file passed to
987  * Extension::exec() or Extension::exec_shared() does not evaluate to
988  * the type expected by the translator, or it is out of range for a
989  * double. Cgu::Extension::ReturnValueError::what() will give further
990  * particulars, in UTF-8 encoding.
991  * @note 1. Prior to versions 2.0.25 and 2.2.8, this translator had a
992  * bug which caused an out-of-range Cgu::Extension::ReturnValueError
993  * to be thrown if any of the numbers in the list to which the scheme
994  * code in the extension file evaluated was 0.0 or a negative number.
995  * This was fixed in versions 2.0.25 and 2.2.8.
996  * @note 2. No native guile exception will arise in this function and
997  * so cause guile to jump out of it if no guile out-of-memory
998  * condition occurs (given that this function is called after a guile
999  * extension task has completed, such a condition is very improbable).
1000  * If such an exception were to arise, the implementation would handle
1001  * it and a C++ exception would be generated in its place in
1002  * Extension::exec() or Extension::exec_shared().
1003  *
1004  * Since 2.0.22 and 2.2.5
1005  */
1006 inline std::vector<double> list_to_vector_double(SCM scm) {
1008  if (scm_is_false(scm_list_p(scm)))
1009  throw ReturnValueError(u8"scheme code did not evaluate to a list\n");
1010 
1011  // nothing in this function should throw a guile exception unless
1012  // there is a guile out-of-memory exception (which is extremely
1013  // improbable). However, let's cover ourselves in case.
1014  scm_dynwind_begin(scm_t_dynwind_flags(0));
1015  // we cannot have a std::vector object in a scope where a guile
1016  // exception might be raised because it has a non-trivial
1017  // destructor, nor can we use RAII. Instead allocate on free store
1018  // and manage the memory by hand until we can no longer jump on a
1019  // guile exception. In addition we cannot store a C++ exception
1020  // using std::exception_ptr because std::exception_ptr is not
1021  // trivially destructible.
1022  bool badalloc = false;
1023  const char* rv_error = 0;
1024  std::vector<double>* res = 0;
1025  VectorDeleteArgs* args = 0;
1026  try {
1027  res = new std::vector<double>;
1028  }
1029  catch (...) {
1030  badalloc = true;
1031  }
1032  if (!badalloc) {
1033  // allocate 'args' on free store, because the continuation in
1034  // which it executes will be up the stack
1035  try {
1036  args = new VectorDeleteArgs{Double, res};
1037  }
1038  catch (...) {
1039  badalloc = true;
1040  }
1041  if (!badalloc) {
1042  // there may be a weakness in guile's implementation here: if
1043  // calling scm_dynwind_unwind_handler() were to give rise to a
1044  // guile out-of-memory exception before the handler is set up by
1045  // it, then we could leak memory allocated from the preceding
1046  // new expressions. Whether that could happen is not documented
1047  // by guile, but because (a) it is so improbable, and (b) once
1048  // we are in out-of-memory land we are already in severe trouble
1049  // and glib is likely to terminate the program at some point
1050  // anyway, it is not worth troubling ourselves over.
1051  scm_dynwind_unwind_handler(&cgu_delete_vector, args, scm_t_wind_flags(0));
1052  int length = scm_to_int(scm_length(scm));
1053  for (int count = 0;
1054  count < length && !rv_error && !badalloc;
1055  ++count) {
1056  SCM item = scm_list_ref(scm, scm_from_int(count));
1057  if (scm_is_false(scm_real_p(item)))
1058  rv_error = u8"scheme code did not evaluate to a homogeneous list of real numbers\n";
1059  else {
1060  SCM min = scm_from_double(std::numeric_limits<double>::lowest());
1061  SCM max = scm_from_double(std::numeric_limits<double>::max());
1062  if (scm_is_false(scm_leq_p(item, max)) || scm_is_false(scm_geq_p(item, min)))
1063  rv_error = u8"scheme code evaluated out of range for double\n";
1064  else {
1065  try {
1066  res->push_back(scm_to_double(item));
1067  }
1068  catch (...) {
1069  badalloc = true;
1070  }
1071  }
1072  }
1073  }
1074  }
1075  }
1076  // all done - no more guile exceptions are possible in this function
1077  // after this so end the dynamic context, take control of the memory
1078  // by RAII and if necessary throw a C++ exception
1079  scm_dynwind_end();
1080  std::unique_ptr<std::vector<double>> up_res(res);
1081  std::unique_ptr<VectorDeleteArgs> up_args(args);
1082  if (badalloc) throw std::bad_alloc();
1083  if (rv_error) throw ReturnValueError(rv_error);
1084  // neither gcc-4.9 nor clang-3.4 will optimize with RVO or move
1085  // semantics here, so force it by hand
1086  return std::move(*res);
1087 }
1088 
1089 /**
1090  * A translator function which can be passed to the third argument of
1091  * Extension::exec() or Extension::exec_shared(). It converts from a
1092  * homogeneous scheme list of strings to a C++ representation of
1093  * std::vector<std::string>. It is thread safe, but see the comments
1094  * above about the thread safety of Extension::exec() and
1095  * Extension::exec_shared().
1096  *
1097  * The returned strings will be in UTF-8 encoding.
1098  *
1099  * Note that the first string in the returned list must not be
1100  * "***cgu-guile-exception***": that string is reserved to the
1101  * implementation.
1102  *
1103  * @param scm An opaque guile SCM object representing the value to
1104  * which the extension file passed to Extension::exec() or
1105  * Extension::exec_shared() evaluated, where that value is a
1106  * homogeneous list of strings.
1107  * @return The std::vector<std::string> representation.
1108  * @exception std::bad_alloc This function might throw std::bad_alloc
1109  * if memory is exhausted and the system throws in that case.
1110  * @exception Cgu::Extension::GuileException This exception will be
1111  * thrown if the scheme code in the extension file passed to
1112  * Extension::exec() or Extension::exec_shared() caused a guile
1113  * exception to be thrown. Cgu::Extension::GuileException::what()
1114  * will give particulars of the guile exception thrown, in UTF-8
1115  * encoding.
1116  * @exception Cgu::Extension::ReturnValueError This exception will be
1117  * thrown if the scheme code in the extension file passed to
1118  * Extension::exec() or Extension::exec_shared() does not evaluate to
1119  * the type expected by the translator.
1120  * Cgu::Extension::ReturnValueError::what() will give further
1121  * particulars, in UTF-8 encoding.
1122  * @note No native guile exception will arise in this function and so
1123  * cause guile to jump out of it if no guile out-of-memory condition
1124  * occurs (given that this function is called after a guile extension
1125  * task has completed, such a condition is very improbable). If such
1126  * an exception were to arise, the implementation would handle it and
1127  * a C++ exception would be generated in its place in
1128  * Extension::exec() or Extension::exec_shared().
1129  *
1130  * Since 2.0.22 and 2.2.5
1131  */
1132 inline std::vector<std::string> list_to_vector_string(SCM scm) {
1134  if (scm_is_false(scm_list_p(scm)))
1135  throw ReturnValueError(u8"scheme code did not evaluate to a list\n");
1136 
1137  // nothing in this function should throw a guile exception unless
1138  // there is a guile out-of-memory exception (which is extremely
1139  // improbable). However, let's cover ourselves in case.
1140  scm_dynwind_begin(scm_t_dynwind_flags(0));
1141  // we cannot have a std::vector object in a scope where a guile
1142  // exception might be raised because it has a non-trivial
1143  // destructor, nor can we use RAII. Instead allocate on free store
1144  // and manage the memory by hand until we can no longer jump on a
1145  // guile exception. In addition we cannot store a C++ exception
1146  // using std::exception_ptr because std::exception_ptr is not
1147  // trivially destructible.
1148  bool badalloc = false;
1149  const char* rv_error = 0;
1150  std::vector<std::string>* res = 0;
1151  VectorDeleteArgs* args = 0;
1152  try {
1153  res = new std::vector<std::string>;
1154  }
1155  catch (...) {
1156  badalloc = true;
1157  }
1158  if (!badalloc) {
1159  // allocate 'args' on free store, because the continuation in
1160  // which it executes will be up the stack
1161  try {
1162  args = new VectorDeleteArgs{String, res};
1163  }
1164  catch (...) {
1165  badalloc = true;
1166  }
1167  if (!badalloc) {
1168  // there may be a weakness in guile's implementation here: if
1169  // calling scm_dynwind_unwind_handler() were to give rise to a
1170  // guile out-of-memory exception before the handler is set up by
1171  // it, then we could leak memory allocated from the preceding
1172  // new expressions. Whether that could happen is not documented
1173  // by guile, but because (a) it is so improbable, and (b) once
1174  // we are in out-of-memory land we are already in severe trouble
1175  // and glib is likely to terminate the program at some point
1176  // anyway, it is not worth troubling ourselves over.
1177  scm_dynwind_unwind_handler(&cgu_delete_vector, args, scm_t_wind_flags(0));
1178  int length = scm_to_int(scm_length(scm));
1179  for (int count = 0;
1180  count < length && !rv_error && !badalloc;
1181  ++count) {
1182  SCM item = scm_list_ref(scm, scm_from_int(count));
1183  if (scm_is_false(scm_string_p(item)))
1184  rv_error = u8"scheme code did not evaluate to a homogeneous list of string\n";
1185  else {
1186  size_t len;
1187  // we don't need a dynwind handler for 'str' because nothing
1188  // after the call to scm_to_utf8_stringn() and before the
1189  // call to free() can cause a guile exception to be raised
1190  char* str = scm_to_utf8_stringn(item, &len);
1191  try {
1192  res->emplace_back(str, len);
1193  }
1194  catch (...) {
1195  badalloc = true;
1196  }
1197  free(str);
1198  }
1199  }
1200  }
1201  }
1202  // all done - no more guile exceptions are possible in this function
1203  // after this so end the dynamic context, take control of the memory
1204  // by RAII and if necessary throw a C++ exception
1205  scm_dynwind_end();
1206  std::unique_ptr<std::vector<std::string>> up_res(res);
1207  std::unique_ptr<VectorDeleteArgs> up_args(args);
1208  if (badalloc) throw std::bad_alloc();
1209  if (rv_error) throw ReturnValueError(rv_error);
1210  // neither gcc-4.9 nor clang-3.4 will optimize with RVO or move
1211  // semantics here, so force it by hand
1212  return std::move(*res);
1213 }
1214 
1215 /**
1216  * A translator function which can be passed to the third argument of
1217  * Extension::exec() or Extension::exec_shared(). It converts from a
1218  * scheme integer to a C++ representation of long. It is thread safe,
1219  * but see the comments above about the thread safety of
1220  * Extension::exec() and Extension::exec_shared().
1221  *
1222  * @param scm An opaque guile SCM object representing the value to
1223  * which the extension file passed to Extension::exec() or
1224  * Extension::exec_shared() evaluated, where that value is an integer.
1225  * @return The C++ long representation.
1226  * @exception std::bad_alloc This function might throw std::bad_alloc
1227  * if memory is exhausted and the system throws in that case.
1228  * @exception Cgu::Extension::GuileException This exception will be
1229  * thrown if the scheme code in the extension file passed to
1230  * Extension::exec() or Extension::exec_shared() caused a guile
1231  * exception to be thrown. Cgu::Extension::GuileException::what()
1232  * will give particulars of the guile exception thrown, in UTF-8
1233  * encoding.
1234  * @exception Cgu::Extension::ReturnValueError This exception will be
1235  * thrown if the scheme code in the extension file passed to
1236  * Extension::exec() or Extension::exec_shared() does not evaluate to
1237  * the type expected by the translator, or it is out of range for a
1238  * long. Cgu::Extension::ReturnValueError::what() will give further
1239  * particulars, in UTF-8 encoding.
1240  * @note No native guile exception will arise in this function and so
1241  * cause guile to jump out of it if no guile out-of-memory condition
1242  * occurs (given that this function is called after a guile extension
1243  * task has completed, such a condition is very improbable). If such
1244  * an exception were to arise, the implementation would handle it and
1245  * a C++ exception would be generated in its place in
1246  * Extension::exec() or Extension::exec_shared().
1247  *
1248  * Since 2.0.22 and 2.2.5
1249  */
1250 inline long integer_to_long(SCM scm) {
1252  if (scm_is_false(scm_integer_p(scm)))
1253  throw ReturnValueError(u8"scheme code did not evaluate to an integer\n");
1254  SCM min = scm_from_long(std::numeric_limits<long>::min());
1255  SCM max = scm_from_long(std::numeric_limits<long>::max());
1256  if (scm_is_false(scm_leq_p(scm, max)) || scm_is_false(scm_geq_p(scm, min)))
1257  throw ReturnValueError(u8"scheme code evaluated out of range for long\n");
1258  return scm_to_long(scm);
1259 }
1260 
1261 /**
1262  * A translator function which can be passed to the third argument of
1263  * Extension::exec() or Extension::exec_shared(). It converts from a
1264  * scheme real number to a C++ representation of double. It is thread
1265  * safe, but see the comments above about the thread safety of
1266  * Extension::exec() and Extension::exec_shared().
1267  *
1268  * @param scm An opaque guile SCM object representing the value to
1269  * which the extension file passed to Extension::exec() or
1270  * Extension::exec_shared() evaluated, where that value is a real
1271  * number.
1272  * @return The C++ double representation.
1273  * @exception std::bad_alloc This function might throw std::bad_alloc
1274  * if memory is exhausted and the system throws in that case.
1275  * @exception Cgu::Extension::GuileException This exception will be
1276  * thrown if the scheme code in the extension file passed to
1277  * Extension::exec() or Extension::exec_shared() caused a guile
1278  * exception to be thrown. Cgu::Extension::GuileException::what()
1279  * will give particulars of the guile exception thrown, in UTF-8
1280  * encoding.
1281  * @exception Cgu::Extension::ReturnValueError This exception will be
1282  * thrown if the scheme code in the extension file passed to
1283  * Extension::exec() or Extension::exec_shared() does not evaluate to
1284  * the type expected by the translator, or it is out of range for a
1285  * double. Cgu::Extension::ReturnValueError::what() will give further
1286  * particulars, in UTF-8 encoding.
1287  * @note 1. Prior to versions 2.0.25 and 2.2.8, this translator had a
1288  * bug which caused an out-of-range Cgu::Extension::ReturnValueError
1289  * to be thrown if the scheme code in the extension file evaluated to
1290  * 0.0 or a negative number. This was fixed in versions 2.0.25 and
1291  * 2.2.8.
1292  * @note 2. No native guile exception will arise in this function and
1293  * so cause guile to jump out of it if no guile out-of-memory
1294  * condition occurs (given that this function is called after a guile
1295  * extension task has completed, such a condition is very improbable).
1296  * If such an exception were to arise, the implementation would handle
1297  * it and a C++ exception would be generated in its place in
1298  * Extension::exec() or Extension::exec_shared().
1299  *
1300  * Since 2.0.22 and 2.2.5
1301  */
1302 inline double real_to_double(SCM scm) {
1304  if (scm_is_false(scm_real_p(scm)))
1305  throw ReturnValueError(u8"scheme code did not evaluate to a real number\n");
1306  SCM min = scm_from_double(std::numeric_limits<double>::lowest());
1307  SCM max = scm_from_double(std::numeric_limits<double>::max());
1308  if (scm_is_false(scm_leq_p(scm, max)) || scm_is_false(scm_geq_p(scm, min)))
1309  throw ReturnValueError(u8"scheme code evaluated out of range for double\n");
1310  return scm_to_double(scm);
1311 }
1312 
1313 /**
1314  * A translator function which can be passed to the third argument of
1315  * Extension::exec() or Extension::exec_shared(). It converts from a
1316  * scheme string to a C++ representation of std::string. It is thread
1317  * safe, but see the comments above about the thread safety of
1318  * Extension::exec() and Extension::exec_shared().
1319  *
1320  * The returned string will be in UTF-8 encoding.
1321  *
1322  * @param scm An opaque guile SCM object representing the value to
1323  * which the extension file passed to Extension::exec() or
1324  * Extension::exec_shared() evaluated, where that value is a string.
1325  * @return The std::string representation.
1326  * @exception std::bad_alloc This function might throw std::bad_alloc
1327  * if memory is exhausted and the system throws in that case.
1328  * @exception Cgu::Extension::GuileException This exception will be
1329  * thrown if the scheme code in the extension file passed to
1330  * Extension::exec() or Extension::exec_shared() caused a guile
1331  * exception to be thrown. Cgu::Extension::GuileException::what()
1332  * will give particulars of the guile exception thrown, in UTF-8
1333  * encoding.
1334  * @exception Cgu::Extension::ReturnValueError This exception will be
1335  * thrown if the scheme code in the extension file passed to
1336  * Extension::exec() or Extension::exec_shared() does not evaluate to
1337  * the type expected by the translator.
1338  * Cgu::Extension::ReturnValueError::what() will give further
1339  * particulars, in UTF-8 encoding.
1340  * @note No native guile exception will arise in this function and so
1341  * cause guile to jump out of it if no guile out-of-memory condition
1342  * occurs (given that this function is called after a guile extension
1343  * task has completed, such a condition is very improbable). If such
1344  * an exception were to arise, the implementation would handle it and
1345  * a C++ exception would be generated in its place in
1346  * Extension::exec() or Extension::exec_shared().
1347  *
1348  * Since 2.0.22 and 2.2.5
1349  */
1350 inline std::string string_to_string(SCM scm) {
1352  if (scm_is_false(scm_string_p(scm)))
1353  throw ReturnValueError(u8"scheme code did not evaluate to a string\n");
1354  size_t len;
1355  // it is safe to use unique_ptr here. If scm_to_utf8_stringn()
1356  // succeeds then nothing after it in this function can cause a guile
1357  // exception.
1358  std::unique_ptr<const char, Cgu::CFree> s(scm_to_utf8_stringn(scm, &len));
1359  return std::string(s.get(), len);
1360 }
1361 
1362 /**
1363  * A translator function which can be passed to the third argument of
1364  * Extension::exec() or Extension::exec_shared(). It disregards the
1365  * scheme value passed to it except to trap any guile exception thrown
1366  * by the scheme task and rethrow it as a C++ exception, and returns a
1367  * NULL void* object. It is thread safe, but see the comments above
1368  * about the thread safety of Extension::exec() and
1369  * Extension::exec_shared().
1370  *
1371  * It is mainly intended for use where the scheme script is executed
1372  * for its side effects, perhaps for I/O, and any communication
1373  * necessary is done by guile exceptions.
1374  *
1375  * @param scm An opaque guile SCM object representing the value to
1376  * which the extension file passed to Extension::exec() or
1377  * Extension::exec_shared() evaluated, which is ignored.
1378  * @return A NULL void* object.
1379  * @exception std::bad_alloc This function might throw std::bad_alloc
1380  * if memory is exhausted and the system throws in that case.
1381  * @exception Cgu::Extension::GuileException This exception will be
1382  * thrown if the scheme code in the extension file passed to
1383  * Extension::exec() or Extension::exec_shared() caused a guile
1384  * exception to be thrown. Cgu::Extension::GuileException::what()
1385  * will give particulars of the guile exception thrown, in UTF-8
1386  * encoding.
1387  * @note No native guile exception will arise in this function and so
1388  * cause guile to jump out of it if no guile out-of-memory condition
1389  * occurs (given that this function is called after a guile extension
1390  * task has completed, such a condition is very improbable). If such
1391  * an exception were to arise, the implementation would handle it and
1392  * a C++ exception would be generated in its place in
1393  * Extension::exec() or Extension::exec_shared().
1394  *
1395  * Since 2.0.22 and 2.2.5
1396  */
1397 inline void* any_to_void(SCM scm) {
1399  return 0;
1400 }
1401 
1402 /**
1403  * This function executes scheme code on the guile VM within a C++
1404  * program using this library. See the introductory remarks above for
1405  * its potential uses, about the thread safety of this function, and
1406  * about the use of the TaskManager::exec_shared() as an alternative.
1407  *
1408  * The first argument to this function is a preamble, which can be
1409  * used to pass top level definitions to the scheme code (in other
1410  * words, for argument passing). It's second argument is the filename
1411  * (with path) of the file containing the scheme code to be executed.
1412  * It's third argument is a translator, which will convert the value
1413  * to which the scheme code evaluates (in C++ terms, its return value)
1414  * to a suitable C++ representation. Preformed translators are
1415  * provided by this library to translate from scheme's integers, real
1416  * numbers and strings to C++ longs, doubles and strings respectively,
1417  * and from any uniform lists of these to C++ vectors of the
1418  * corresponding type. There is also a translator for void return
1419  * types. See the introductory remarks above for more information
1420  * about translators.
1421  *
1422  * Any native guile exceptions thrown by the code executed by this
1423  * function (and by any code which it calls) are converted and
1424  * rethrown as C++ exceptions.
1425  *
1426  * The scheme file can call other scheme code, and load modules, in
1427  * the ordinary way. Thus, this function can execute any scheme code
1428  * which guile can execute as a program, and the programmer can (if
1429  * wanted) act on its return value in the C++ code which invokes it.
1430  *
1431  * Thread cancellation is blocked for the thread in which this
1432  * function executes until this function returns.
1433  *
1434  * @param preamble Scheme code such as top level definitions to be
1435  * seen by the code in the file to be executed. This is mainly
1436  * intended for argument passing, but can comprise any valid scheme
1437  * code. It can also be empty (you can pass ""). Any string literals
1438  * must be in UTF-8 encoding.
1439  * @param file The file which is to be executed on the guile VM. This
1440  * should include the full pathname or a pathname relative to the
1441  * current directory. The contents of the file, and in particular any
1442  * string literals in it, must be in UTF-8 encoding. The filename and
1443  * path must also be given in UTF-8 encoding, even if the local
1444  * filename encoding is something different: guile will convert the
1445  * UTF-8 name which it is given to its own internal string encoding
1446  * using unicode code points, and then convert that to locale encoding
1447  * on looking up the filename. However sticking to ASCII for
1448  * filenames and paths (which is always valid UTF-8) will maximise
1449  * portability. The file name can be empty (you can pass ""), in
1450  * which case only the preamble will be evaluated (but for efficiency
1451  * reasons any complex code not at the top level should be included in
1452  * the file rather than in the preamble).
1453  * @param translator The function or callable object which will
1454  * convert the value to which the scheme code evaluates to a C++
1455  * representation which will be returned by this function. The
1456  * translator should take a single argument comprising an opaque guile
1457  * object of type SCM, and return the C++ representation for it.
1458  * @return The C++ representation returned by the translator.
1459  * @exception std::bad_alloc This function might throw std::bad_alloc
1460  * if memory is exhausted and the system throws in that case.
1461  * @exception Cgu::Extension::GuileException This exception will be
1462  * thrown if the scheme code in 'file' (or called by it) throws a
1463  * guile exception. Cgu::Extension::GuileException::what() will give
1464  * particulars of the guile exception thrown, in UTF-8 encoding.
1465  * @exception Cgu::Extension::ReturnValueError This exception will be
1466  * thrown if the code in 'file' does not evaluate to the type expected
1467  * by the translator. Cgu::Extension::ReturnValueError::what() will
1468  * give further particulars, in UTF-8 encoding.
1469  * @exception Cgu::Extension::WrapperError This exception will be
1470  * thrown if a custom translator throws a native guile exception or a
1471  * C++ exception not comprising Extension::GuileException or
1472  * Extension::ReturnValueError, one of the preformed translators
1473  * throws std::bad_alloc or encounters a guile out-of-memory
1474  * exception, assigning to an internal exception description string
1475  * throws std::bad_alloc, or evaluation of the preamble throws a
1476  * native guile exception.
1477  *
1478  * Since 2.0.22 and 2.2.5
1479  */
1480 template <class Translator>
1481 auto exec(const std::string& preamble,
1482  const std::string& file,
1483  Translator&& translator) -> typename std::result_of<Translator(SCM)>::type {
1484  typedef typename std::result_of<Translator(SCM)>::type Ret;
1485  return exec_impl<Ret>(preamble, file, std::forward<Translator>(translator), false);
1486 }
1487 
1488 /**
1489  * This function executes scheme code on the guile VM within a C++
1490  * program using this library. See the introductory remarks above for
1491  * its potential uses, about the thread safety of this function, and
1492  * about the use of the TaskManager::exec() as an alternative.
1493  *
1494  * The first argument to this function is a preamble, which can be
1495  * used to pass top level definitions to the scheme code (in other
1496  * words, for argument passing). It's second argument is the filename
1497  * (with path) of the file containing the scheme code to be executed.
1498  * It's third argument is a translator, which will convert the value
1499  * to which the scheme code evaluates (in C++ terms, its return value)
1500  * to a suitable C++ representation. Preformed translators are
1501  * provided by this library to translate from scheme's integers, real
1502  * numbers and strings to C++ longs, doubles and strings respectively,
1503  * and from any uniform lists of these to C++ vectors of the
1504  * corresponding type. There is also a translator for void return
1505  * types. See the introductory remarks above for more information
1506  * about translators.
1507  *
1508  * Any native guile exceptions thrown by the code executed by this
1509  * function (and by any code which it calls) are converted and
1510  * rethrown as C++ exceptions.
1511  *
1512  * The scheme file can call other scheme code, and load modules, in
1513  * the ordinary way. Thus, this function can execute any scheme code
1514  * which guile can execute as a program, and the programmer can (if
1515  * wanted) act on its return value in the C++ code which invokes it.
1516  *
1517  * Thread cancellation is blocked for the thread in which this
1518  * function executes until this function returns.
1519  *
1520  * @param preamble Scheme code such as top level definitions to be
1521  * seen by the code in the file to be executed. This is mainly
1522  * intended for argument passing, but can comprise any valid scheme
1523  * code. It can also be empty (you can pass ""). Any string literals
1524  * must be in UTF-8 encoding.
1525  * @param file The file which is to be executed on the guile VM. This
1526  * should include the full pathname or a pathname relative to the
1527  * current directory. The contents of the file, and in particular any
1528  * string literals in it, must be in UTF-8 encoding. The filename and
1529  * path must also be given in UTF-8 encoding, even if the local
1530  * filename encoding is something different: guile will convert the
1531  * UTF-8 name which it is given to its own internal string encoding
1532  * using unicode code points, and then convert that to locale encoding
1533  * on looking up the filename. However sticking to ASCII for
1534  * filenames and paths (which is always valid UTF-8) will maximise
1535  * portability. The file name can be empty (you can pass ""), in
1536  * which case only the preamble will be evaluated.
1537  * @param translator The function or callable object which will
1538  * convert the value to which the scheme code evaluates to a C++
1539  * representation which will be returned by this function. The
1540  * translator should take a single argument comprising an opaque guile
1541  * object of type SCM, and return the C++ representation for it.
1542  * @return The C++ representation returned by the translator.
1543  * @exception std::bad_alloc This function might throw std::bad_alloc
1544  * if memory is exhausted and the system throws in that case.
1545  * @exception Cgu::Extension::GuileException This exception will be
1546  * thrown if the scheme code in 'file' (or called by it) throws a
1547  * guile exception. Cgu::Extension::GuileException::what() will give
1548  * particulars of the guile exception thrown, in UTF-8 encoding.
1549  * @exception Cgu::Extension::ReturnValueError This exception will be
1550  * thrown if the code in 'file' does not evaluate to the type expected
1551  * by the translator. Cgu::Extension::ReturnValueError::what() will
1552  * give further particulars, in UTF-8 encoding.
1553  * @exception Cgu::Extension::WrapperError This exception will be
1554  * thrown if a custom translator throws a native guile exception or a
1555  * C++ exception not comprising Extension::GuileException or
1556  * Extension::ReturnValueError, one of the preformed translators
1557  * throws std::bad_alloc or encounters a guile out-of-memory
1558  * exception, assigning to an internal exception description string
1559  * throws std::bad_alloc, or evaluation of the preamble throws a
1560  * native guile exception.
1561  *
1562  * Since 2.0.24 and 2.2.7
1563  */
1564 template <class Translator>
1565 auto exec_shared(const std::string& preamble,
1566  const std::string& file,
1567  Translator&& translator) -> typename std::result_of<Translator(SCM)>::type {
1568  typedef typename std::result_of<Translator(SCM)>::type Ret;
1569  return exec_impl<Ret>(preamble, file, std::forward<Translator>(translator), true);
1570 }
1571 
1572 } // namespace Extension
1573 
1574 } // namespace Cgu
1575 
1576 #endif // CGU_EXTENSION_H