OSDN Git Service

In gcc/:
[pf3gnuchains/gcc-fork.git] / gcc / doc / objc.texi
1 @c Copyright (C) 1988, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
2 @c 1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
3 @c This is part of the GCC manual.
4 @c For copying conditions, see the file gcc.texi.
5
6 @node Objective-C
7 @comment  node-name,  next,  previous,  up
8
9 @chapter GNU Objective-C features
10
11 This document is meant to describe some of the GNU Objective-C
12 features.  It is not intended to teach you Objective-C, there are
13 several resources on the Internet that present the language.
14
15 @menu
16 * Executing code before main::
17 * Type encoding::
18 * Garbage Collection::
19 * Constant string objects::
20 * compatibility_alias::
21 * Exceptions::
22 * Synchronization::
23 @end menu
24
25 @node Executing code before main
26 @section @code{+load}: Executing code before main
27
28 The GNU Objective-C runtime provides a way that allows you to execute
29 code before the execution of the program enters the @code{main}
30 function.  The code is executed on a per-class and a per-category basis,
31 through a special class method @code{+load}.
32
33 This facility is very useful if you want to initialize global variables
34 which can be accessed by the program directly, without sending a message
35 to the class first.  The usual way to initialize global variables, in the
36 @code{+initialize} method, might not be useful because
37 @code{+initialize} is only called when the first message is sent to a
38 class object, which in some cases could be too late.
39
40 Suppose for example you have a @code{FileStream} class that declares
41 @code{Stdin}, @code{Stdout} and @code{Stderr} as global variables, like
42 below:
43
44 @smallexample
45
46 FileStream *Stdin = nil;
47 FileStream *Stdout = nil;
48 FileStream *Stderr = nil;
49
50 @@implementation FileStream
51
52 + (void)initialize
53 @{
54     Stdin = [[FileStream new] initWithFd:0];
55     Stdout = [[FileStream new] initWithFd:1];
56     Stderr = [[FileStream new] initWithFd:2];
57 @}
58
59 /* @r{Other methods here} */
60 @@end
61
62 @end smallexample
63
64 In this example, the initialization of @code{Stdin}, @code{Stdout} and
65 @code{Stderr} in @code{+initialize} occurs too late.  The programmer can
66 send a message to one of these objects before the variables are actually
67 initialized, thus sending messages to the @code{nil} object.  The
68 @code{+initialize} method which actually initializes the global
69 variables is not invoked until the first message is sent to the class
70 object.  The solution would require these variables to be initialized
71 just before entering @code{main}.
72
73 The correct solution of the above problem is to use the @code{+load}
74 method instead of @code{+initialize}:
75
76 @smallexample
77
78 @@implementation FileStream
79
80 + (void)load
81 @{
82     Stdin = [[FileStream new] initWithFd:0];
83     Stdout = [[FileStream new] initWithFd:1];
84     Stderr = [[FileStream new] initWithFd:2];
85 @}
86
87 /* @r{Other methods here} */
88 @@end
89
90 @end smallexample
91
92 The @code{+load} is a method that is not overridden by categories.  If a
93 class and a category of it both implement @code{+load}, both methods are
94 invoked.  This allows some additional initializations to be performed in
95 a category.
96
97 This mechanism is not intended to be a replacement for @code{+initialize}.
98 You should be aware of its limitations when you decide to use it
99 instead of @code{+initialize}.
100
101 @menu
102 * What you can and what you cannot do in +load::
103 @end menu
104
105
106 @node What you can and what you cannot do in +load
107 @subsection What you can and what you cannot do in @code{+load}
108
109 The @code{+load} implementation in the GNU runtime guarantees you the following
110 things:
111
112 @itemize @bullet
113
114 @item
115 you can write whatever C code you like;
116
117 @item
118 you can send messages to Objective-C constant strings (@code{@@"this is a
119 constant string"});
120
121 @item
122 you can allocate and send messages to objects whose class is implemented
123 in the same file;
124
125 @item
126 the @code{+load} implementation of all super classes of a class are executed before the @code{+load} of that class is executed;
127
128 @item
129 the @code{+load} implementation of a class is executed before the
130 @code{+load} implementation of any category.
131
132 @end itemize
133
134 In particular, the following things, even if they can work in a
135 particular case, are not guaranteed:
136
137 @itemize @bullet
138
139 @item
140 allocation of or sending messages to arbitrary objects;
141
142 @item
143 allocation of or sending messages to objects whose classes have a
144 category implemented in the same file;
145
146 @end itemize
147
148 You should make no assumptions about receiving @code{+load} in sibling
149 classes when you write @code{+load} of a class.  The order in which
150 sibling classes receive @code{+load} is not guaranteed.
151
152 The order in which @code{+load} and @code{+initialize} are called could
153 be problematic if this matters.  If you don't allocate objects inside
154 @code{+load}, it is guaranteed that @code{+load} is called before
155 @code{+initialize}.  If you create an object inside @code{+load} the
156 @code{+initialize} method of object's class is invoked even if
157 @code{+load} was not invoked.  Note if you explicitly call @code{+load}
158 on a class, @code{+initialize} will be called first.  To avoid possible
159 problems try to implement only one of these methods.
160
161 The @code{+load} method is also invoked when a bundle is dynamically
162 loaded into your running program.  This happens automatically without any
163 intervening operation from you.  When you write bundles and you need to
164 write @code{+load} you can safely create and send messages to objects whose
165 classes already exist in the running program.  The same restrictions as
166 above apply to classes defined in bundle.
167
168
169
170 @node Type encoding
171 @section Type encoding
172
173 The Objective-C compiler generates type encodings for all the
174 types.  These type encodings are used at runtime to find out information
175 about selectors and methods and about objects and classes.
176
177 The types are encoded in the following way:
178
179 @c @sp 1
180
181 @multitable @columnfractions .25 .75
182 @item @code{_Bool}
183 @tab @code{B}
184 @item @code{char}
185 @tab @code{c}
186 @item @code{unsigned char}
187 @tab @code{C}
188 @item @code{short}
189 @tab @code{s}
190 @item @code{unsigned short}
191 @tab @code{S}
192 @item @code{int}
193 @tab @code{i}
194 @item @code{unsigned int}
195 @tab @code{I}
196 @item @code{long}
197 @tab @code{l}
198 @item @code{unsigned long}
199 @tab @code{L}
200 @item @code{long long}
201 @tab @code{q}
202 @item @code{unsigned long long}
203 @tab @code{Q}
204 @item @code{float}
205 @tab @code{f}
206 @item @code{double}
207 @tab @code{d}
208 @item @code{void}
209 @tab @code{v}
210 @item @code{id}
211 @tab @code{@@}
212 @item @code{Class}
213 @tab @code{#}
214 @item @code{SEL}
215 @tab @code{:}
216 @item @code{char*}
217 @tab @code{*}
218 @item unknown type
219 @tab @code{?}
220 @item Complex types
221 @tab @code{j} followed by the inner type.  For example @code{_Complex double} is encoded as "jd".
222 @item bit-fields
223 @tab @code{b} followed by the starting position of the bit-field, the type of the bit-field and the size of the bit-field (the bit-fields encoding was changed from the NeXT's compiler encoding, see below)
224 @end multitable
225
226 @c @sp 1
227
228 The encoding of bit-fields has changed to allow bit-fields to be properly
229 handled by the runtime functions that compute sizes and alignments of
230 types that contain bit-fields.  The previous encoding contained only the
231 size of the bit-field.  Using only this information it is not possible to
232 reliably compute the size occupied by the bit-field.  This is very
233 important in the presence of the Boehm's garbage collector because the
234 objects are allocated using the typed memory facility available in this
235 collector.  The typed memory allocation requires information about where
236 the pointers are located inside the object.
237
238 The position in the bit-field is the position, counting in bits, of the
239 bit closest to the beginning of the structure.
240
241 The non-atomic types are encoded as follows:
242
243 @c @sp 1
244
245 @multitable @columnfractions .2 .8
246 @item pointers
247 @tab @samp{^} followed by the pointed type.
248 @item arrays
249 @tab @samp{[} followed by the number of elements in the array followed by the type of the elements followed by @samp{]}
250 @item structures
251 @tab @samp{@{} followed by the name of the structure (or @samp{?} if the structure is unnamed), the @samp{=} sign, the type of the members and by @samp{@}}
252 @item unions
253 @tab @samp{(} followed by the name of the structure (or @samp{?} if the union is unnamed), the @samp{=} sign, the type of the members followed by @samp{)}
254 @end multitable
255
256 Here are some types and their encodings, as they are generated by the
257 compiler on an i386 machine:
258
259 @sp 1
260
261 @multitable @columnfractions .25 .75
262 @item Objective-C type
263 @tab Compiler encoding
264 @item
265 @smallexample
266 int a[10];
267 @end smallexample
268 @tab @code{[10i]}
269 @item
270 @smallexample
271 struct @{
272   int i;
273   float f[3];
274   int a:3;
275   int b:2;
276   char c;
277 @}
278 @end smallexample
279 @tab @code{@{?=i[3f]b128i3b131i2c@}}
280 @end multitable
281
282 @sp 1
283
284 In addition to the types the compiler also encodes the type
285 specifiers.  The table below describes the encoding of the current
286 Objective-C type specifiers:
287
288 @sp 1
289
290 @multitable @columnfractions .25 .75
291 @item Specifier
292 @tab Encoding
293 @item @code{const}
294 @tab @code{r}
295 @item @code{in}
296 @tab @code{n}
297 @item @code{inout}
298 @tab @code{N}
299 @item @code{out}
300 @tab @code{o}
301 @item @code{bycopy}
302 @tab @code{O}
303 @item @code{oneway}
304 @tab @code{V}
305 @end multitable
306
307 @sp 1
308
309 The type specifiers are encoded just before the type.  Unlike types
310 however, the type specifiers are only encoded when they appear in method
311 argument types.
312
313
314 @node Garbage Collection
315 @section Garbage Collection
316
317 Support for garbage collection with the GNU runtime has been added by
318 using a powerful conservative garbage collector, known as the
319 Boehm-Demers-Weiser conservative garbage collector.
320
321 To enable the support for it you have to configure the compiler using
322 an additional argument, @w{@option{--enable-objc-gc}}.  This will
323 build the boehm-gc library, and build an additional runtime library
324 which has several enhancements to support the garbage collector.  The
325 new library has a new name, @file{libobjc_gc.a} to not conflict with
326 the non-garbage-collected library.
327
328 When the garbage collector is used, the objects are allocated using the
329 so-called typed memory allocation mechanism available in the
330 Boehm-Demers-Weiser collector.  This mode requires precise information on
331 where pointers are located inside objects.  This information is computed
332 once per class, immediately after the class has been initialized.
333
334 There is a new runtime function @code{class_ivar_set_gcinvisible()}
335 which can be used to declare a so-called @dfn{weak pointer}
336 reference.  Such a pointer is basically hidden for the garbage collector;
337 this can be useful in certain situations, especially when you want to
338 keep track of the allocated objects, yet allow them to be
339 collected.  This kind of pointers can only be members of objects, you
340 cannot declare a global pointer as a weak reference.  Every type which is
341 a pointer type can be declared a weak pointer, including @code{id},
342 @code{Class} and @code{SEL}.
343
344 Here is an example of how to use this feature.  Suppose you want to
345 implement a class whose instances hold a weak pointer reference; the
346 following class does this:
347
348 @smallexample
349
350 @@interface WeakPointer : Object
351 @{
352     const void* weakPointer;
353 @}
354
355 - initWithPointer:(const void*)p;
356 - (const void*)weakPointer;
357 @@end
358
359
360 @@implementation WeakPointer
361
362 + (void)initialize
363 @{
364   class_ivar_set_gcinvisible (self, "weakPointer", YES);
365 @}
366
367 - initWithPointer:(const void*)p
368 @{
369   weakPointer = p;
370   return self;
371 @}
372
373 - (const void*)weakPointer
374 @{
375   return weakPointer;
376 @}
377
378 @@end
379
380 @end smallexample
381
382 Weak pointers are supported through a new type character specifier
383 represented by the @samp{!} character.  The
384 @code{class_ivar_set_gcinvisible()} function adds or removes this
385 specifier to the string type description of the instance variable named
386 as argument.
387
388 @c =========================================================================
389 @node Constant string objects
390 @section Constant string objects
391
392 GNU Objective-C provides constant string objects that are generated
393 directly by the compiler.  You declare a constant string object by
394 prefixing a C constant string with the character @samp{@@}:
395
396 @smallexample
397   id myString = @@"this is a constant string object";
398 @end smallexample
399
400 The constant string objects are by default instances of the
401 @code{NXConstantString} class which is provided by the GNU Objective-C
402 runtime.  To get the definition of this class you must include the
403 @file{objc/NXConstStr.h} header file.
404
405 User defined libraries may want to implement their own constant string
406 class.  To be able to support them, the GNU Objective-C compiler provides
407 a new command line options @option{-fconstant-string-class=@var{class-name}}.
408 The provided class should adhere to a strict structure, the same
409 as @code{NXConstantString}'s structure:
410
411 @smallexample
412
413 @@interface MyConstantStringClass
414 @{
415   Class isa;
416   char *c_string;
417   unsigned int len;
418 @}
419 @@end
420
421 @end smallexample
422
423 @code{NXConstantString} inherits from @code{Object}; user class
424 libraries may choose to inherit the customized constant string class
425 from a different class than @code{Object}.  There is no requirement in
426 the methods the constant string class has to implement, but the final
427 ivar layout of the class must be the compatible with the given
428 structure.
429
430 When the compiler creates the statically allocated constant string
431 object, the @code{c_string} field will be filled by the compiler with
432 the string; the @code{length} field will be filled by the compiler with
433 the string length; the @code{isa} pointer will be filled with
434 @code{NULL} by the compiler, and it will later be fixed up automatically
435 at runtime by the GNU Objective-C runtime library to point to the class
436 which was set by the @option{-fconstant-string-class} option when the
437 object file is loaded (if you wonder how it works behind the scenes, the
438 name of the class to use, and the list of static objects to fixup, are
439 stored by the compiler in the object file in a place where the GNU
440 runtime library will find them at runtime).
441
442 As a result, when a file is compiled with the
443 @option{-fconstant-string-class} option, all the constant string objects
444 will be instances of the class specified as argument to this option.  It
445 is possible to have multiple compilation units referring to different
446 constant string classes, neither the compiler nor the linker impose any
447 restrictions in doing this.
448
449 @c =========================================================================
450 @node compatibility_alias
451 @section compatibility_alias
452
453 The keyword @code{@@compatibility_alias} allows you to define a class name
454 as equivalent to another class name.  For example:
455
456 @smallexample
457 @@compatibility_alias WOApplication GSWApplication;
458 @end smallexample
459
460 tells the compiler that each time it encounters @code{WOApplication} as
461 a class name, it should replace it with @code{GSWApplication} (that is,
462 @code{WOApplication} is just an alias for @code{GSWApplication}).
463
464 There are some constraints on how this can be used---
465
466 @itemize @bullet
467
468 @item @code{WOApplication} (the alias) must not be an existing class;
469
470 @item @code{GSWApplication} (the real class) must be an existing class.
471
472 @end itemize
473
474 @c =========================================================================
475 @node Exceptions
476 @section Exceptions
477
478 GNU Objective-C provides exception support built into the language, as
479 in the following example:
480
481 @smallexample
482   @@try @{
483     @dots{}
484        @@throw expr;
485     @dots{}
486   @}
487   @@catch (AnObjCClass *exc) @{
488     @dots{}
489       @@throw expr;
490     @dots{}
491       @@throw;
492     @dots{}
493   @}
494   @@catch (AnotherClass *exc) @{
495     @dots{}
496   @}
497   @@catch (id allOthers) @{
498     @dots{}
499   @}
500   @@finally @{
501     @dots{}
502       @@throw expr;
503     @dots{}
504   @}
505 @end smallexample
506
507 The @code{@@throw} statement may appear anywhere in an Objective-C or
508 Objective-C++ program; when used inside of a @code{@@catch} block, the
509 @code{@@throw} may appear without an argument (as shown above), in
510 which case the object caught by the @code{@@catch} will be rethrown.
511
512 Note that only (pointers to) Objective-C objects may be thrown and
513 caught using this scheme.  When an object is thrown, it will be caught
514 by the nearest @code{@@catch} clause capable of handling objects of
515 that type, analogously to how @code{catch} blocks work in C++ and
516 Java.  A @code{@@catch(id @dots{})} clause (as shown above) may also
517 be provided to catch any and all Objective-C exceptions not caught by
518 previous @code{@@catch} clauses (if any).
519
520 The @code{@@finally} clause, if present, will be executed upon exit
521 from the immediately preceding @code{@@try @dots{} @@catch} section.
522 This will happen regardless of whether any exceptions are thrown,
523 caught or rethrown inside the @code{@@try @dots{} @@catch} section,
524 analogously to the behavior of the @code{finally} clause in Java.
525
526 There are several caveats to using the new exception mechanism:
527
528 @itemize @bullet
529 @item
530 The @option{-fobjc-exceptions} command line option must be used when
531 compiling Objective-C files that use exceptions.
532
533 @item
534 With the GNU runtime, exceptions are always implemented as ``native''
535 exceptions and it is recommended that the @option{-fexceptions} and
536 @option{-shared-libgcc} options are used when linking.
537
538 @item
539 With the NeXT runtime, although currently designed to be binary
540 compatible with @code{NS_HANDLER}-style idioms provided by the
541 @code{NSException} class, the new exceptions can only be used on Mac
542 OS X 10.3 (Panther) and later systems, due to additional functionality
543 needed in the NeXT Objective-C runtime.
544
545 @item
546 As mentioned above, the new exceptions do not support handling
547 types other than Objective-C objects.   Furthermore, when used from
548 Objective-C++, the Objective-C exception model does not interoperate with C++
549 exceptions at this time.  This means you cannot @code{@@throw} an exception
550 from Objective-C and @code{catch} it in C++, or vice versa
551 (i.e., @code{throw @dots{} @@catch}).
552 @end itemize
553
554 @c =========================================================================
555 @node Synchronization
556 @section Synchronization
557
558 GNU Objective-C provides support for synchronized blocks:
559
560 @smallexample
561   @@synchronized (ObjCClass *guard) @{
562     @dots{}
563   @}
564 @end smallexample
565
566 Upon entering the @code{@@synchronized} block, a thread of execution
567 shall first check whether a lock has been placed on the corresponding
568 @code{guard} object by another thread.  If it has, the current thread
569 shall wait until the other thread relinquishes its lock.  Once
570 @code{guard} becomes available, the current thread will place its own
571 lock on it, execute the code contained in the @code{@@synchronized}
572 block, and finally relinquish the lock (thereby making @code{guard}
573 available to other threads).
574
575 Unlike Java, Objective-C does not allow for entire methods to be
576 marked @code{@@synchronized}.  Note that throwing exceptions out of
577 @code{@@synchronized} blocks is allowed, and will cause the guarding
578 object to be unlocked properly.
579
580 Because of the interactions between synchronization and exception
581 handling, you can only use @code{@@synchronized} when compiling with
582 exceptions enabled, that is with the command line option
583 @option{-fobjc-exceptions}.