libguile-program.texi 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. @c -*-texinfo-*-
  2. @c This is part of the GNU Guile Reference Manual.
  3. @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005
  4. @c Free Software Foundation, Inc.
  5. @c See the file guile.texi for copying conditions.
  6. @node Programming Overview
  7. @section An Overview of Guile Programming
  8. Guile is designed as an extension language interpreter that is
  9. straightforward to integrate with applications written in C (and C++).
  10. The big win here for the application developer is that Guile
  11. integration, as the Guile web page says, ``lowers your project's
  12. hacktivation energy.'' Lowering the hacktivation energy means that you,
  13. as the application developer, @emph{and your users}, reap the benefits
  14. that flow from being able to extend the application in a high level
  15. extension language rather than in plain old C.
  16. In abstract terms, it's difficult to explain what this really means and
  17. what the integration process involves, so instead let's begin by jumping
  18. straight into an example of how you might integrate Guile into an
  19. existing program, and what you could expect to gain by so doing. With
  20. that example under our belts, we'll then return to a more general
  21. analysis of the arguments involved and the range of programming options
  22. available.
  23. @menu
  24. * Extending Dia:: How one might extend Dia using Guile.
  25. * Scheme vs C:: Why Scheme is more hackable than C.
  26. * Testbed Example:: Example: using Guile in a testbed.
  27. * Programming Options:: Options for Guile programming.
  28. * User Programming:: How about application users?
  29. @end menu
  30. @node Extending Dia
  31. @subsection How One Might Extend Dia Using Guile
  32. Dia is a free software program for drawing schematic diagrams like flow
  33. charts and floor plans (@uref{http://www.gnome.org/projects/dia/}).
  34. This section conducts the thought
  35. experiment of adding Guile to Dia. In so doing, it aims to illustrate
  36. several of the steps and considerations involved in adding Guile to
  37. applications in general.
  38. @menu
  39. * Dia Objective:: Deciding why you want to add Guile.
  40. * Dia Steps:: Four steps required to add Guile.
  41. * Dia Smobs:: How to represent Dia data in Scheme.
  42. * Dia Primitives:: Writing Guile primitives for Dia.
  43. * Dia Hook:: Providing a hook for Scheme evaluation.
  44. * Dia Structure:: Overall structure for adding Guile.
  45. * Dia Advanced:: Going further with Dia and Guile.
  46. @end menu
  47. @node Dia Objective
  48. @subsubsection Deciding Why You Want to Add Guile
  49. First off, you should understand why you want to add Guile to Dia at
  50. all, and that means forming a picture of what Dia does and how it does
  51. it. So, what are the constituents of the Dia application?
  52. @itemize @bullet
  53. @item
  54. Most importantly, the @dfn{application domain objects} --- in other
  55. words, the concepts that differentiate Dia from another application such
  56. as a word processor or spreadsheet: shapes, templates, connectors,
  57. pages, plus the properties of all these things.
  58. @item
  59. The code that manages the graphical face of the application, including
  60. the layout and display of the objects above.
  61. @item
  62. The code that handles input events, which indicate that the application
  63. user is wanting to do something.
  64. @end itemize
  65. @noindent
  66. (In other words, a textbook example of the @dfn{model - view -
  67. controller} paradigm.)
  68. Next question: how will Dia benefit once the Guile integration is
  69. complete? Several (positive!) answers are possible here, and the choice
  70. is obviously up to the application developers. Still, one answer is
  71. that the main benefit will be the ability to manipulate Dia's
  72. application domain objects from Scheme.
  73. Suppose that Dia made a set of procedures available in Scheme,
  74. representing the most basic operations on objects such as shapes,
  75. connectors, and so on. Using Scheme, the application user could then
  76. write code that builds upon these basic operations to create more
  77. complex procedures. For example, given basic procedures to enumerate
  78. the objects on a page, to determine whether an object is a square, and
  79. to change the fill pattern of a single shape, the user can write a
  80. Scheme procedure to change the fill pattern of all squares on the
  81. current page:
  82. @lisp
  83. (define (change-squares'-fill-pattern new-pattern)
  84. (for-each-shape current-page
  85. (lambda (shape)
  86. (if (square? shape)
  87. (change-fill-pattern shape new-pattern)))))
  88. @end lisp
  89. @node Dia Steps
  90. @subsubsection Four Steps Required to Add Guile
  91. Assuming this objective, four steps are needed to achieve it.
  92. First, you need a way of representing your application-specific objects
  93. --- such as @code{shape} in the previous example --- when they are
  94. passed into the Scheme world. Unless your objects are so simple that
  95. they map naturally into builtin Scheme data types like numbers and
  96. strings, you will probably want to use Guile's @dfn{SMOB} interface to
  97. create a new Scheme data type for your objects.
  98. Second, you need to write code for the basic operations like
  99. @code{for-each-shape} and @code{square?} such that they access and
  100. manipulate your existing data structures correctly, and then make these
  101. operations available as @dfn{primitives} on the Scheme level.
  102. Third, you need to provide some mechanism within the Dia application
  103. that a user can hook into to cause arbitrary Scheme code to be
  104. evaluated.
  105. Finally, you need to restructure your top-level application C code a
  106. little so that it initializes the Guile interpreter correctly and
  107. declares your @dfn{SMOBs} and @dfn{primitives} to the Scheme world.
  108. The following subsections expand on these four points in turn.
  109. @node Dia Smobs
  110. @subsubsection How to Represent Dia Data in Scheme
  111. For all but the most trivial applications, you will probably want to
  112. allow some representation of your domain objects to exist on the Scheme
  113. level. This is where the idea of SMOBs comes in, and with it issues of
  114. lifetime management and garbage collection.
  115. To get more concrete about this, let's look again at the example we gave
  116. earlier of how application users can use Guile to build higher-level
  117. functions from the primitives that Dia itself provides.
  118. @lisp
  119. (define (change-squares'-fill-pattern new-pattern)
  120. (for-each-shape current-page
  121. (lambda (shape)
  122. (if (square? shape)
  123. (change-fill-pattern shape new-pattern)))))
  124. @end lisp
  125. Consider what is stored here in the variable @code{shape}. For each
  126. shape on the current page, the @code{for-each-shape} primitive calls
  127. @code{(lambda (shape) @dots{})} with an argument representing that
  128. shape. Question is: how is that argument represented on the Scheme
  129. level? The issues are as follows.
  130. @itemize @bullet
  131. @item
  132. Whatever the representation, it has to be decodable again by the C code
  133. for the @code{square?} and @code{change-fill-pattern} primitives. In
  134. other words, a primitive like @code{square?} has somehow to be able to
  135. turn the value that it receives back into something that points to the
  136. underlying C structure describing a shape.
  137. @item
  138. The representation must also cope with Scheme code holding on to the
  139. value for later use. What happens if the Scheme code stores
  140. @code{shape} in a global variable, but then that shape is deleted (in a
  141. way that the Scheme code is not aware of), and later on some other
  142. Scheme code uses that global variable again in a call to, say,
  143. @code{square?}?
  144. @item
  145. The lifetime and memory allocation of objects that exist @emph{only} in
  146. the Scheme world is managed automatically by Guile's garbage collector
  147. using one simple rule: when there are no remaining references to an
  148. object, the object is considered dead and so its memory is freed. But
  149. for objects that exist in both C and Scheme, the picture is more
  150. complicated; in the case of Dia, where the @code{shape} argument passes
  151. transiently in and out of the Scheme world, it would be quite wrong the
  152. @strong{delete} the underlying C shape just because the Scheme code has
  153. finished evaluation. How do we avoid this happening?
  154. @end itemize
  155. One resolution of these issues is for the Scheme-level representation of
  156. a shape to be a new, Scheme-specific C structure wrapped up as a SMOB.
  157. The SMOB is what is passed into and out of Scheme code, and the
  158. Scheme-specific C structure inside the SMOB points to Dia's underlying C
  159. structure so that the code for primitives like @code{square?} can get at
  160. it.
  161. To cope with an underlying shape being deleted while Scheme code is
  162. still holding onto a Scheme shape value, the underlying C structure
  163. should have a new field that points to the Scheme-specific SMOB. When a
  164. shape is deleted, the relevant code chains through to the
  165. Scheme-specific structure and sets its pointer back to the underlying
  166. structure to NULL. Thus the SMOB value for the shape continues to
  167. exist, but any primitive code that tries to use it will detect that the
  168. underlying shape has been deleted because the underlying structure
  169. pointer is NULL.
  170. So, to summarize the steps involved in this resolution of the problem
  171. (and assuming that the underlying C structure for a shape is
  172. @code{struct dia_shape}):
  173. @itemize @bullet
  174. @item
  175. Define a new Scheme-specific structure that @emph{points} to the
  176. underlying C structure:
  177. @lisp
  178. struct dia_guile_shape
  179. @{
  180. struct dia_shape * c_shape; /* NULL => deleted */
  181. @}
  182. @end lisp
  183. @item
  184. Add a field to @code{struct dia_shape} that points to its @code{struct
  185. dia_guile_shape} if it has one ---
  186. @lisp
  187. struct dia_shape
  188. @{
  189. @dots{}
  190. struct dia_guile_shape * guile_shape;
  191. @}
  192. @end lisp
  193. @noindent
  194. --- so that C code can set @code{guile_shape->c_shape} to NULL when the
  195. underlying shape is deleted.
  196. @item
  197. Wrap @code{struct dia_guile_shape} as a SMOB type.
  198. @item
  199. Whenever you need to represent a C shape onto the Scheme level, create a
  200. SMOB instance for it, and pass that.
  201. @item
  202. In primitive code that receives a shape SMOB instance, check the
  203. @code{c_shape} field when decoding it, to find out whether the
  204. underlying C shape is still there.
  205. @end itemize
  206. As far as memory management is concerned, the SMOB values and their
  207. Scheme-specific structures are under the control of the garbage
  208. collector, whereas the underlying C structures are explicitly managed in
  209. exactly the same way that Dia managed them before we thought of adding
  210. Guile.
  211. When the garbage collector decides to free a shape SMOB value, it calls
  212. the @dfn{SMOB free} function that was specified when defining the shape
  213. SMOB type. To maintain the correctness of the @code{guile_shape} field
  214. in the underlying C structure, this function should chain through to the
  215. underlying C structure (if it still exists) and set its
  216. @code{guile_shape} field to NULL.
  217. For full documentation on defining and using SMOB types, see
  218. @ref{Defining New Types (Smobs)}.
  219. @node Dia Primitives
  220. @subsubsection Writing Guile Primitives for Dia
  221. Once the details of object representation are decided, writing the
  222. primitive function code that you need is usually straightforward.
  223. A primitive is simply a C function whose arguments and return value are
  224. all of type @code{SCM}, and whose body does whatever you want it to do.
  225. As an example, here is a possible implementation of the @code{square?}
  226. primitive:
  227. @lisp
  228. static SCM square_p (SCM shape)
  229. @{
  230. struct dia_guile_shape * guile_shape;
  231. /* Check that arg is really a shape SMOB. */
  232. scm_assert_smob_type (shape_tag, shape);
  233. /* Access Scheme-specific shape structure. */
  234. guile_shape = SCM_SMOB_DATA (shape);
  235. /* Find out if underlying shape exists and is a
  236. square; return answer as a Scheme boolean. */
  237. return scm_from_bool (guile_shape->c_shape &&
  238. (guile_shape->c_shape->type == DIA_SQUARE));
  239. @}
  240. @end lisp
  241. Notice how easy it is to chain through from the @code{SCM shape}
  242. parameter that @code{square_p} receives --- which is a SMOB --- to the
  243. Scheme-specific structure inside the SMOB, and thence to the underlying
  244. C structure for the shape.
  245. In this code, @code{scm_assert_smob_type}, @code{SCM_SMOB_DATA}, and
  246. @code{scm_from_bool} are from the standard Guile API. We assume that
  247. @code{shape_tag} was given to us when we made the shape SMOB type, using
  248. @code{scm_make_smob_type}. The call to @code{scm_assert_smob_type}
  249. ensures that @var{shape} is indeed a shape. This is needed to guard
  250. against Scheme code using the @code{square?} procedure incorrectly, as
  251. in @code{(square? "hello")}; Scheme's latent typing means that usage
  252. errors like this must be caught at run time.
  253. Having written the C code for your primitives, you need to make them
  254. available as Scheme procedures by calling the @code{scm_c_define_gsubr}
  255. function. @code{scm_c_define_gsubr} (@pxref{Primitive Procedures}) takes arguments that
  256. specify the Scheme-level name for the primitive and how many required,
  257. optional and rest arguments it can accept. The @code{square?} primitive
  258. always requires exactly one argument, so the call to make it available
  259. in Scheme reads like this:
  260. @lisp
  261. scm_c_define_gsubr ("square?", 1, 0, 0, square_p);
  262. @end lisp
  263. For where to put this call, see the subsection after next on the
  264. structure of Guile-enabled code (@pxref{Dia Structure}).
  265. @node Dia Hook
  266. @subsubsection Providing a Hook for the Evaluation of Scheme Code
  267. To make the Guile integration useful, you have to design some kind of
  268. hook into your application that application users can use to cause their
  269. Scheme code to be evaluated.
  270. Technically, this is straightforward; you just have to decide on a
  271. mechanism that is appropriate for your application. Think of Emacs, for
  272. example: when you type @kbd{@key{ESC} :}, you get a prompt where you can
  273. type in any Elisp code, which Emacs will then evaluate. Or, again like
  274. Emacs, you could provide a mechanism (such as an init file) to allow
  275. Scheme code to be associated with a particular key sequence, and
  276. evaluate the code when that key sequence is entered.
  277. In either case, once you have the Scheme code that you want to evaluate,
  278. as a null terminated string, you can tell Guile to evaluate it by
  279. calling the @code{scm_c_eval_string} function.
  280. @node Dia Structure
  281. @subsubsection Top-level Structure of Guile-enabled Dia
  282. Let's assume that the pre-Guile Dia code looks structurally like this:
  283. @itemize @bullet
  284. @item
  285. @code{main ()}
  286. @itemize @bullet
  287. @item
  288. do lots of initialization and setup stuff
  289. @item
  290. enter Gtk main loop
  291. @end itemize
  292. @end itemize
  293. When you add Guile to a program, one (rather technical) requirement is
  294. that Guile's garbage collector needs to know where the bottom of the C
  295. stack is. The easiest way to ensure this is to use
  296. @code{scm_boot_guile} like this:
  297. @itemize @bullet
  298. @item
  299. @code{main ()}
  300. @itemize @bullet
  301. @item
  302. do lots of initialization and setup stuff
  303. @item
  304. @code{scm_boot_guile (argc, argv, inner_main, NULL)}
  305. @end itemize
  306. @item
  307. @code{inner_main ()}
  308. @itemize @bullet
  309. @item
  310. define all SMOB types
  311. @item
  312. export primitives to Scheme using @code{scm_c_define_gsubr}
  313. @item
  314. enter Gtk main loop
  315. @end itemize
  316. @end itemize
  317. In other words, you move the guts of what was previously in your
  318. @code{main} function into a new function called @code{inner_main}, and
  319. then add a @code{scm_boot_guile} call, with @code{inner_main} as a
  320. parameter, to the end of @code{main}.
  321. Assuming that you are using SMOBs and have written primitive code as
  322. described in the preceding subsections, you also need to insert calls to
  323. declare your new SMOBs and export the primitives to Scheme. These
  324. declarations must happen @emph{inside} the dynamic scope of the
  325. @code{scm_boot_guile} call, but also @emph{before} any code is run that
  326. could possibly use them --- the beginning of @code{inner_main} is an
  327. ideal place for this.
  328. @node Dia Advanced
  329. @subsubsection Going Further with Dia and Guile
  330. The steps described so far implement an initial Guile integration that
  331. already gives a lot of additional power to Dia application users. But
  332. there are further steps that you could take, and it's interesting to
  333. consider a few of these.
  334. In general, you could progressively move more of Dia's source code from
  335. C into Scheme. This might make the code more maintainable and
  336. extensible, and it could open the door to new programming paradigms that
  337. are tricky to effect in C but straightforward in Scheme.
  338. A specific example of this is that you could use the guile-gtk package,
  339. which provides Scheme-level procedures for most of the Gtk+ library, to
  340. move the code that lays out and displays Dia objects from C to Scheme.
  341. As you follow this path, it naturally becomes less useful to maintain a
  342. distinction between Dia's original non-Guile-related source code, and
  343. its later code implementing SMOBs and primitives for the Scheme world.
  344. For example, suppose that the original source code had a
  345. @code{dia_change_fill_pattern} function:
  346. @lisp
  347. void dia_change_fill_pattern (struct dia_shape * shape,
  348. struct dia_pattern * pattern)
  349. @{
  350. /* real pattern change work */
  351. @}
  352. @end lisp
  353. During initial Guile integration, you add a @code{change_fill_pattern}
  354. primitive for Scheme purposes, which accesses the underlying structures
  355. from its SMOB values and uses @code{dia_change_fill_pattern} to do the
  356. real work:
  357. @lisp
  358. SCM change_fill_pattern (SCM shape, SCM pattern)
  359. @{
  360. struct dia_shape * d_shape;
  361. struct dia_pattern * d_pattern;
  362. @dots{}
  363. dia_change_fill_pattern (d_shape, d_pattern);
  364. return SCM_UNSPECIFIED;
  365. @}
  366. @end lisp
  367. At this point, it makes sense to keep @code{dia_change_fill_pattern} and
  368. @code{change_fill_pattern} separate, because
  369. @code{dia_change_fill_pattern} can also be called without going through
  370. Scheme at all, say because the user clicks a button which causes a
  371. C-registered Gtk+ callback to be called.
  372. But, if the code for creating buttons and registering their callbacks is
  373. moved into Scheme (using guile-gtk), it may become true that
  374. @code{dia_change_fill_pattern} can no longer be called other than
  375. through Scheme. In which case, it makes sense to abolish it and move
  376. its contents directly into @code{change_fill_pattern}, like this:
  377. @lisp
  378. SCM change_fill_pattern (SCM shape, SCM pattern)
  379. @{
  380. struct dia_shape * d_shape;
  381. struct dia_pattern * d_pattern;
  382. @dots{}
  383. /* real pattern change work */
  384. return SCM_UNSPECIFIED;
  385. @}
  386. @end lisp
  387. So further Guile integration progressively @emph{reduces} the amount of
  388. functional C code that you have to maintain over the long term.
  389. A similar argument applies to data representation. In the discussion of
  390. SMOBs earlier, issues arose because of the different memory management
  391. and lifetime models that normally apply to data structures in C and in
  392. Scheme. However, with further Guile integration, you can resolve this
  393. issue in a more radical way by allowing all your data structures to be
  394. under the control of the garbage collector, and kept alive by references
  395. from the Scheme world. Instead of maintaining an array or linked list
  396. of shapes in C, you would instead maintain a list in Scheme.
  397. Rather like the coalescing of @code{dia_change_fill_pattern} and
  398. @code{change_fill_pattern}, the practical upshot of such a change is
  399. that you would no longer have to keep the @code{dia_shape} and
  400. @code{dia_guile_shape} structures separate, and so wouldn't need to
  401. worry about the pointers between them. Instead, you could change the
  402. SMOB definition to wrap the @code{dia_shape} structure directly, and
  403. send @code{dia_guile_shape} off to the scrap yard. Cut out the middle
  404. man!
  405. Finally, we come to the holy grail of Guile's free software / extension
  406. language approach. Once you have a Scheme representation for
  407. interesting Dia data types like shapes, and a handy bunch of primitives
  408. for manipulating them, it suddenly becomes clear that you have a bundle
  409. of functionality that could have far-ranging use beyond Dia itself. In
  410. other words, the data types and primitives could now become a library,
  411. and Dia becomes just one of the many possible applications using that
  412. library --- albeit, at this early stage, a rather important one!
  413. In this model, Guile becomes just the glue that binds everything
  414. together. Imagine an application that usefully combined functionality
  415. from Dia, Gnumeric and GnuCash --- it's tricky right now, because no
  416. such application yet exists; but it'll happen some day @dots{}
  417. @node Scheme vs C
  418. @subsection Why Scheme is More Hackable Than C
  419. Underlying Guile's value proposition is the assumption that programming
  420. in a high level language, specifically Guile's implementation of Scheme,
  421. is necessarily better in some way than programming in C. What do we
  422. mean by this claim, and how can we be so sure?
  423. One class of advantages applies not only to Scheme, but more generally
  424. to any interpretable, high level, scripting language, such as Emacs
  425. Lisp, Python, Ruby, or @TeX{}'s macro language. Common features of all
  426. such languages, when compared to C, are that:
  427. @itemize @bullet
  428. @item
  429. They lend themselves to rapid and experimental development cycles,
  430. owing usually to a combination of their interpretability and the
  431. integrated development environment in which they are used.
  432. @item
  433. They free developers from some of the low level bookkeeping tasks
  434. associated with C programming, notably memory management.
  435. @item
  436. They provide high level features such as container objects and exception
  437. handling that make common programming tasks easier.
  438. @end itemize
  439. In the case of Scheme, particular features that make programming easier
  440. --- and more fun! --- are its powerful mechanisms for abstracting parts
  441. of programs (closures --- @pxref{About Closure}) and for iteration
  442. (@pxref{while do}).
  443. The evidence in support of this argument is empirical: the huge amount
  444. of code that has been written in extension languages for applications
  445. that support this mechanism. Most notable are extensions written in
  446. Emacs Lisp for GNU Emacs, in @TeX{}'s macro language for @TeX{}, and in
  447. Script-Fu for the Gimp, but there is increasingly now a significant code
  448. eco-system for Guile-based applications as well, such as Lilypond and
  449. GnuCash. It is close to inconceivable that similar amounts of
  450. functionality could have been added to these applications just by
  451. writing new code in their base implementation languages.
  452. @node Testbed Example
  453. @subsection Example: Using Guile for an Application Testbed
  454. As an example of what this means in practice, imagine writing a testbed
  455. for an application that is tested by submitting various requests (via a
  456. C interface) and validating the output received. Suppose further that
  457. the application keeps an idea of its current state, and that the
  458. ``correct'' output for a given request may depend on the current
  459. application state. A complete ``white box''@footnote{A @dfn{white box}
  460. test plan is one that incorporates knowledge of the internal design of
  461. the application under test.} test plan for this application would aim to
  462. submit all possible requests in each distinguishable state, and validate
  463. the output for all request/state combinations.
  464. To write all this test code in C would be very tedious. Suppose instead
  465. that the testbed code adds a single new C function, to submit an
  466. arbitrary request and return the response, and then uses Guile to export
  467. this function as a Scheme procedure. The rest of the testbed can then
  468. be written in Scheme, and so benefits from all the advantages of
  469. programming in Scheme that were described in the previous section.
  470. (In this particular example, there is an additional benefit of writing
  471. most of the testbed in Scheme. A common problem for white box testing
  472. is that mistakes and mistaken assumptions in the application under test
  473. can easily be reproduced in the testbed code. It is more difficult to
  474. copy mistakes like this when the testbed is written in a different
  475. language from the application.)
  476. @node Programming Options
  477. @subsection A Choice of Programming Options
  478. The preceding arguments and example point to a model of Guile
  479. programming that is applicable in many cases. According to this model,
  480. Guile programming involves a balance between C and Scheme programming,
  481. with the aim being to extract the greatest possible Scheme level benefit
  482. from the least amount of C level work.
  483. The C level work required in this model usually consists of packaging
  484. and exporting functions and application objects such that they can be
  485. seen and manipulated on the Scheme level. To help with this, Guile's C
  486. language interface includes utility features that aim to make this kind
  487. of integration very easy for the application developer. These features
  488. are documented later in this part of the manual: see REFFIXME.
  489. This model, though, is really just one of a range of possible
  490. programming options. If all of the functionality that you need is
  491. available from Scheme, you could choose instead to write your whole
  492. application in Scheme (or one of the other high level languages that
  493. Guile supports through translation), and simply use Guile as an
  494. interpreter for Scheme. (In the future, we hope that Guile will also be
  495. able to compile Scheme code, so lessening the performance gap between C
  496. and Scheme code.) Or, at the other end of the C--Scheme scale, you
  497. could write the majority of your application in C, and only call out to
  498. Guile occasionally for specific actions such as reading a configuration
  499. file or executing a user-specified extension. The choices boil down to
  500. two basic questions:
  501. @itemize @bullet
  502. @item
  503. Which parts of the application do you write in C, and which in Scheme
  504. (or another high level translated language)?
  505. @item
  506. How do you design the interface between the C and Scheme parts of your
  507. application?
  508. @end itemize
  509. These are of course design questions, and the right design for any given
  510. application will always depend upon the particular requirements that you
  511. are trying to meet. In the context of Guile, however, there are some
  512. generally applicable considerations that can help you when designing
  513. your answers.
  514. @menu
  515. * Available Functionality:: What functionality is already available?
  516. * Basic Constraints:: Functional and performance constraints.
  517. * Style Choices:: Your preferred programming style.
  518. * Program Control:: What controls program execution?
  519. @end menu
  520. @node Available Functionality
  521. @subsubsection What Functionality is Already Available?
  522. Suppose, for the sake of argument, that you would prefer to write your
  523. whole application in Scheme. Then the API available to you consists of:
  524. @itemize @bullet
  525. @item
  526. standard Scheme
  527. @item
  528. plus the extensions to standard Scheme provided by
  529. Guile in its core distribution
  530. @item
  531. plus any additional functionality that you or others have packaged so
  532. that it can be loaded as a Guile Scheme module.
  533. @end itemize
  534. A module in the last category can either be a pure Scheme module --- in
  535. other words a collection of utility procedures coded in Scheme --- or a
  536. module that provides a Scheme interface to an extension library coded in
  537. C --- in other words a nice package where someone else has done the work
  538. of wrapping up some useful C code for you. The set of available modules
  539. is growing quickly and already includes such useful examples as
  540. @code{(gtk gtk)}, which makes Gtk+ drawing functions available in
  541. Scheme, and @code{(database postgres)}, which provides SQL access to a
  542. Postgres database.
  543. Given the growing collection of pre-existing modules, it is quite
  544. feasible that your application could be implemented by combining a
  545. selection of these modules together with new application code written in
  546. Scheme.
  547. If this approach is not enough, because the functionality that your
  548. application needs is not already available in this form, and it is
  549. impossible to write the new functionality in Scheme, you will need to
  550. write some C code. If the required function is already available in C
  551. (e.g.@: in a library), all you need is a little glue to connect it to the
  552. world of Guile. If not, you need both to write the basic code and to
  553. plumb it into Guile.
  554. In either case, two general considerations are important. Firstly, what
  555. is the interface by which the functionality is presented to the Scheme
  556. world? Does the interface consist only of function calls (for example,
  557. a simple drawing interface), or does it need to include @dfn{objects} of
  558. some kind that can be passed between C and Scheme and manipulated by
  559. both worlds. Secondly, how does the lifetime and memory management of
  560. objects in the C code relate to the garbage collection governed approach
  561. of Scheme objects? In the case where the basic C code is not already
  562. written, most of the difficulties of memory management can be avoided by
  563. using Guile's C interface features from the start.
  564. For the full documentation on writing C code for Guile and connecting
  565. existing C code to the Guile world, see REFFIXME.
  566. @node Basic Constraints
  567. @subsubsection Functional and Performance Constraints
  568. @node Style Choices
  569. @subsubsection Your Preferred Programming Style
  570. @node Program Control
  571. @subsubsection What Controls Program Execution?
  572. @node User Programming
  573. @subsection How About Application Users?
  574. So far we have considered what Guile programming means for an
  575. application developer. But what if you are instead @emph{using} an
  576. existing Guile-based application, and want to know what your
  577. options are for programming and extending this application?
  578. The answer to this question varies from one application to another,
  579. because the options available depend inevitably on whether the
  580. application developer has provided any hooks for you to hang your own
  581. code on and, if there are such hooks, what they allow you to
  582. do.@footnote{Of course, in the world of free software, you always have
  583. the freedom to modify the application's source code to your own
  584. requirements. Here we are concerned with the extension options that the
  585. application has provided for without your needing to modify its source
  586. code.} For example@dots{}
  587. @itemize @bullet
  588. @item
  589. If the application permits you to load and execute any Guile code, the
  590. world is your oyster. You can extend the application in any way that
  591. you choose.
  592. @item
  593. A more cautious application might allow you to load and execute Guile
  594. code, but only in a @dfn{safe} environment, where the interface
  595. available is restricted by the application from the standard Guile API.
  596. @item
  597. Or a really fearful application might not provide a hook to really
  598. execute user code at all, but just use Scheme syntax as a convenient way
  599. for users to specify application data or configuration options.
  600. @end itemize
  601. In the last two cases, what you can do is, by definition, restricted by
  602. the application, and you should refer to the application's own manual to
  603. find out your options.
  604. The most well known example of the first case is Emacs, with its
  605. extension language Emacs Lisp: as well as being a text editor, Emacs
  606. supports the loading and execution of arbitrary Emacs Lisp code. The
  607. result of such openness has been dramatic: Emacs now benefits from
  608. user-contributed Emacs Lisp libraries that extend the basic editing
  609. function to do everything from reading news to psychoanalysis and
  610. playing adventure games. The only limitation is that extensions are
  611. restricted to the functionality provided by Emacs's built-in set of
  612. primitive operations. For example, you can interact and display data by
  613. manipulating the contents of an Emacs buffer, but you can't pop-up and
  614. draw a window with a layout that is totally different to the Emacs
  615. standard.
  616. This situation with a Guile application that supports the loading of
  617. arbitrary user code is similar, except perhaps even more so, because
  618. Guile also supports the loading of extension libraries written in C.
  619. This last point enables user code to add new primitive operations to
  620. Guile, and so to bypass the limitation present in Emacs Lisp.
  621. At this point, the distinction between an application developer and an
  622. application user becomes rather blurred. Instead of seeing yourself as
  623. a user extending an application, you could equally well say that you are
  624. developing a new application of your own using some of the primitive
  625. functionality provided by the original application. As such, all the
  626. discussions of the preceding sections of this chapter are relevant to
  627. how you can proceed with developing your extension.
  628. @c Local Variables:
  629. @c TeX-master: "guile.texi"
  630. @c End: