libguile-program.texi 31 KB

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