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 * GNU Objective-C runtime API::
17 * Executing code before main::
18 * Type encoding::
19 * Garbage Collection::
20 * Constant string objects::
21 * compatibility_alias::
22 * Exceptions::
23 * Synchronization::
24 * Fast enumeration::
25 * Messaging with the GNU Objective-C runtime::
26 @end menu
27
28 @c =========================================================================
29 @node GNU Objective-C runtime API
30 @section GNU Objective-C runtime API
31
32 This section is specific for the GNU Objective-C runtime.  If you are
33 using a different runtime, you can skip it.
34
35 The GNU Objective-C runtime provides an API that allows you to
36 interact with the Objective-C runtime system, querying the live
37 runtime structures and even manipulating them.  This allows you for
38 example to inspect and navigate classes, methods and protocols; to
39 define new classes or new methods, and even to modify existing classes
40 or protocols.
41
42 If you are using a ``Foundation'' library such as GNUstep-Base, this
43 library will provide you with a rich set of functionality to do most
44 of the inspection tasks, and you probably will only need direct access
45 to the GNU Objective-C runtime API to define new classes or methods.
46
47 @menu
48 * Modern GNU Objective-C runtime API::
49 * Traditional GNU Objective-C runtime API::
50 @end menu
51
52 @c =========================================================================
53 @node Modern GNU Objective-C runtime API
54 @subsection Modern GNU Objective-C runtime API
55
56 The GNU Objective-C runtime provides an API which is similar to the
57 one provided by the ``Objective-C 2.0'' Apple/NeXT Objective-C
58 runtime.  The API is documented in the public header files of the GNU
59 Objective-C runtime:
60
61 @itemize @bullet
62
63 @item
64 @file{objc/objc.h}: this is the basic Objective-C header file,
65 defining the basic Objective-C types such as @code{id}, @code{Class}
66 and @code{BOOL}.  You have to include this header to do almost
67 anything with Objective-C.
68
69 @item
70 @file{objc/runtime.h}: this header declares most of the public runtime
71 API functions allowing you to inspect and manipulate the Objective-C
72 runtime data structures.  These functions are fairly standardized
73 across Objective-C runtimes and are almost identical to the Apple/NeXT
74 Objective-C runtime ones.  It does not declare functions in some
75 specialized areas (constructing and forwarding message invocations,
76 threading) which are in the other headers below.  You have to include
77 @file{objc/objc.h} and @file{objc/runtime.h} to use any of the
78 functions, such as @code{class_getName()}, declared in
79 @file{objc/runtime.h}.
80
81 @item
82 @file{objc/message.h}: this header declares public functions used to
83 construct, deconstruct and forward message invocations.  Because
84 messaging is done in quite a different way on different runtimes,
85 functions in this header are specific to the GNU Objective-C runtime
86 implementation.
87
88 @item
89 @file{objc/objc-exception.h}: this header declares some public
90 functions related to Objective-C exceptions.  For example functions in
91 this header allow you to throw an Objective-C exception from plain
92 C/C++ code.
93
94 @item
95 @file{objc/objc-sync.h}: this header declares some public functions
96 related to the Objective-C @code{@@synchronized()} syntax, allowing
97 you to emulate an Objective-C @code{@@synchronized()} block in plain
98 C/C++ code.
99
100 @item
101 @file{objc/thr.h}: this header declares a public runtime API threading
102 layer that is only provided by the GNU Objective-C runtime.  It
103 declares functions such as @code{objc_mutex_lock()}, which provide a
104 platform-independent set of threading functions.
105
106 @end itemize
107
108 The header files contain detailed documentation for each function in
109 the GNU Objective-C runtime API.
110
111 @c =========================================================================
112 @node Traditional GNU Objective-C runtime API
113 @subsection Traditional GNU Objective-C runtime API
114
115 The GNU Objective-C runtime used to provide a different API, which we
116 call the ``traditional'' GNU Objective-C runtime API.  Functions
117 belonging to this API are easy to recognize because they use a
118 different naming convention, such as @code{class_get_super_class()}
119 (traditional API) instead of @code{class_getSuperclass()} (modern
120 API).  Software using this API includes the file
121 @file{objc/objc-api.h} where it is declared.
122
123 The traditional API is deprecated but it is still supported in this
124 release of the runtime; you can access it as usual by including
125 @file{objc/objc-api.h}.
126
127 If you are using the traditional API you are urged to upgrade your
128 software to use the modern API because the traditional API requires
129 access to private runtime internals to do anything serious with it;
130 for this reason, there is no guarantee that future releases of the GNU
131 Objective-C runtime library will be able to provide a fully compatible
132 @file{objc/objc-api.h} as the private runtime internals change.  It is
133 expected that the next release will hide a number of runtime internals
134 making the traditional API nominally supported but fairly useless
135 beyond very simple use cases.
136
137 Finally, you can not include both @file{objc/objc-api.h} and
138 @file{objc/runtime.h} at the same time.  The traditional and modern
139 APIs unfortunately have some conflicting declarations (such as the one
140 for @code{Method}) and can not be used at the same time.
141
142 @c =========================================================================
143 @node Executing code before main
144 @section @code{+load}: Executing code before main
145
146 This section is specific for the GNU Objective-C runtime.  If you are
147 using a different runtime, you can skip it.
148
149 The GNU Objective-C runtime provides a way that allows you to execute
150 code before the execution of the program enters the @code{main}
151 function.  The code is executed on a per-class and a per-category basis,
152 through a special class method @code{+load}.
153
154 This facility is very useful if you want to initialize global variables
155 which can be accessed by the program directly, without sending a message
156 to the class first.  The usual way to initialize global variables, in the
157 @code{+initialize} method, might not be useful because
158 @code{+initialize} is only called when the first message is sent to a
159 class object, which in some cases could be too late.
160
161 Suppose for example you have a @code{FileStream} class that declares
162 @code{Stdin}, @code{Stdout} and @code{Stderr} as global variables, like
163 below:
164
165 @smallexample
166
167 FileStream *Stdin = nil;
168 FileStream *Stdout = nil;
169 FileStream *Stderr = nil;
170
171 @@implementation FileStream
172
173 + (void)initialize
174 @{
175     Stdin = [[FileStream new] initWithFd:0];
176     Stdout = [[FileStream new] initWithFd:1];
177     Stderr = [[FileStream new] initWithFd:2];
178 @}
179
180 /* @r{Other methods here} */
181 @@end
182
183 @end smallexample
184
185 In this example, the initialization of @code{Stdin}, @code{Stdout} and
186 @code{Stderr} in @code{+initialize} occurs too late.  The programmer can
187 send a message to one of these objects before the variables are actually
188 initialized, thus sending messages to the @code{nil} object.  The
189 @code{+initialize} method which actually initializes the global
190 variables is not invoked until the first message is sent to the class
191 object.  The solution would require these variables to be initialized
192 just before entering @code{main}.
193
194 The correct solution of the above problem is to use the @code{+load}
195 method instead of @code{+initialize}:
196
197 @smallexample
198
199 @@implementation FileStream
200
201 + (void)load
202 @{
203     Stdin = [[FileStream new] initWithFd:0];
204     Stdout = [[FileStream new] initWithFd:1];
205     Stderr = [[FileStream new] initWithFd:2];
206 @}
207
208 /* @r{Other methods here} */
209 @@end
210
211 @end smallexample
212
213 The @code{+load} is a method that is not overridden by categories.  If a
214 class and a category of it both implement @code{+load}, both methods are
215 invoked.  This allows some additional initializations to be performed in
216 a category.
217
218 This mechanism is not intended to be a replacement for @code{+initialize}.
219 You should be aware of its limitations when you decide to use it
220 instead of @code{+initialize}.
221
222 @menu
223 * What you can and what you cannot do in +load::
224 @end menu
225
226
227 @node What you can and what you cannot do in +load
228 @subsection What you can and what you cannot do in @code{+load}
229
230 @code{+load} is to be used only as a last resort.  Because it is
231 executed very early, most of the Objective-C runtime machinery will
232 not be ready when @code{+load} is executed; hence @code{+load} works
233 best for executing C code that is independent on the Objective-C
234 runtime.
235
236 The @code{+load} implementation in the GNU runtime guarantees you the
237 following things:
238
239 @itemize @bullet
240
241 @item
242 you can write whatever C code you like;
243
244 @item
245 you can allocate and send messages to objects whose class is implemented
246 in the same file;
247
248 @item
249 the @code{+load} implementation of all super classes of a class are
250 executed before the @code{+load} of that class is executed;
251
252 @item
253 the @code{+load} implementation of a class is executed before the
254 @code{+load} implementation of any category.
255
256 @end itemize
257
258 In particular, the following things, even if they can work in a
259 particular case, are not guaranteed:
260
261 @itemize @bullet
262
263 @item
264 allocation of or sending messages to arbitrary objects;
265
266 @item
267 allocation of or sending messages to objects whose classes have a
268 category implemented in the same file;
269
270 @item
271 sending messages to Objective-C constant strings (@code{@@"this is a
272 constant string"});
273
274 @end itemize
275
276 You should make no assumptions about receiving @code{+load} in sibling
277 classes when you write @code{+load} of a class.  The order in which
278 sibling classes receive @code{+load} is not guaranteed.
279
280 The order in which @code{+load} and @code{+initialize} are called could
281 be problematic if this matters.  If you don't allocate objects inside
282 @code{+load}, it is guaranteed that @code{+load} is called before
283 @code{+initialize}.  If you create an object inside @code{+load} the
284 @code{+initialize} method of object's class is invoked even if
285 @code{+load} was not invoked.  Note if you explicitly call @code{+load}
286 on a class, @code{+initialize} will be called first.  To avoid possible
287 problems try to implement only one of these methods.
288
289 The @code{+load} method is also invoked when a bundle is dynamically
290 loaded into your running program.  This happens automatically without any
291 intervening operation from you.  When you write bundles and you need to
292 write @code{+load} you can safely create and send messages to objects whose
293 classes already exist in the running program.  The same restrictions as
294 above apply to classes defined in bundle.
295
296
297
298 @node Type encoding
299 @section Type encoding
300
301 This is an advanced section.  Type encodings are used extensively by
302 the compiler and by the runtime, but you generally do not need to know
303 about them to use Objective-C.
304
305 The Objective-C compiler generates type encodings for all the types.
306 These type encodings are used at runtime to find out information about
307 selectors and methods and about objects and classes.
308
309 The types are encoded in the following way:
310
311 @c @sp 1
312
313 @multitable @columnfractions .25 .75
314 @item @code{_Bool}
315 @tab @code{B}
316 @item @code{char}
317 @tab @code{c}
318 @item @code{unsigned char}
319 @tab @code{C}
320 @item @code{short}
321 @tab @code{s}
322 @item @code{unsigned short}
323 @tab @code{S}
324 @item @code{int}
325 @tab @code{i}
326 @item @code{unsigned int}
327 @tab @code{I}
328 @item @code{long}
329 @tab @code{l}
330 @item @code{unsigned long}
331 @tab @code{L}
332 @item @code{long long}
333 @tab @code{q}
334 @item @code{unsigned long long}
335 @tab @code{Q}
336 @item @code{float}
337 @tab @code{f}
338 @item @code{double}
339 @tab @code{d}
340 @item @code{long double}
341 @tab @code{D}
342 @item @code{void}
343 @tab @code{v}
344 @item @code{id}
345 @tab @code{@@}
346 @item @code{Class}
347 @tab @code{#}
348 @item @code{SEL}
349 @tab @code{:}
350 @item @code{char*}
351 @tab @code{*}
352 @item @code{enum}
353 @tab an @code{enum} is encoded exactly as the integer type that the compiler uses for it, which depends on the enumeration
354 values.  Often the compiler users @code{unsigned int}, which is then encoded as @code{I}.
355 @item unknown type
356 @tab @code{?}
357 @item Complex types
358 @tab @code{j} followed by the inner type.  For example @code{_Complex double} is encoded as "jd".
359 @item bit-fields
360 @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)
361 @end multitable
362
363 @c @sp 1
364
365 The encoding of bit-fields has changed to allow bit-fields to be
366 properly handled by the runtime functions that compute sizes and
367 alignments of types that contain bit-fields.  The previous encoding
368 contained only the size of the bit-field.  Using only this information
369 it is not possible to reliably compute the size occupied by the
370 bit-field.  This is very important in the presence of the Boehm's
371 garbage collector because the objects are allocated using the typed
372 memory facility available in this collector.  The typed memory
373 allocation requires information about where the pointers are located
374 inside the object.
375
376 The position in the bit-field is the position, counting in bits, of the
377 bit closest to the beginning of the structure.
378
379 The non-atomic types are encoded as follows:
380
381 @c @sp 1
382
383 @multitable @columnfractions .2 .8
384 @item pointers
385 @tab @samp{^} followed by the pointed type.
386 @item arrays
387 @tab @samp{[} followed by the number of elements in the array followed by the type of the elements followed by @samp{]}
388 @item structures
389 @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{@}}
390 @item unions
391 @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{)}
392 @item vectors
393 @tab @samp{![} followed by the vector_size (the number of bytes composing the vector) followed by a comma, followed by the alignment (in bytes) of the vector, followed by the type of the elements followed by @samp{]}
394 @end multitable
395
396 Here are some types and their encodings, as they are generated by the
397 compiler on an i386 machine:
398
399 @sp 1
400
401 @multitable @columnfractions .25 .75
402 @item Objective-C type
403 @tab Compiler encoding
404 @item
405 @smallexample
406 int a[10];
407 @end smallexample
408 @tab @code{[10i]}
409 @item
410 @smallexample
411 struct @{
412   int i;
413   float f[3];
414   int a:3;
415   int b:2;
416   char c;
417 @}
418 @end smallexample
419 @tab @code{@{?=i[3f]b128i3b131i2c@}}
420 @item
421 @smallexample
422 int a __attribute__ ((vector_size (16)));
423 @end smallexample
424 @tab @code{![16,16i]} (alignment would depend on the machine)
425 @end multitable
426
427 @sp 1
428
429 In addition to the types the compiler also encodes the type
430 specifiers.  The table below describes the encoding of the current
431 Objective-C type specifiers:
432
433 @sp 1
434
435 @multitable @columnfractions .25 .75
436 @item Specifier
437 @tab Encoding
438 @item @code{const}
439 @tab @code{r}
440 @item @code{in}
441 @tab @code{n}
442 @item @code{inout}
443 @tab @code{N}
444 @item @code{out}
445 @tab @code{o}
446 @item @code{bycopy}
447 @tab @code{O}
448 @item @code{byref}
449 @tab @code{R}
450 @item @code{oneway}
451 @tab @code{V}
452 @end multitable
453
454 @sp 1
455
456 The type specifiers are encoded just before the type.  Unlike types
457 however, the type specifiers are only encoded when they appear in method
458 argument types.
459
460 Note how @code{const} interacts with pointers:
461
462 @sp 1
463
464 @multitable @columnfractions .25 .75
465 @item Objective-C type
466 @tab Compiler encoding
467 @item
468 @smallexample
469 const int
470 @end smallexample
471 @tab @code{ri}
472 @item
473 @smallexample
474 const int*
475 @end smallexample
476 @tab @code{^ri}
477 @item
478 @smallexample
479 int *const
480 @end smallexample
481 @tab @code{r^i}
482 @end multitable
483
484 @sp 1
485
486 @code{const int*} is a pointer to a @code{const int}, and so is
487 encoded as @code{^ri}.  @code{int* const}, instead, is a @code{const}
488 pointer to an @code{int}, and so is encoded as @code{r^i}.
489
490 Finally, there is a complication when encoding @code{const char *}
491 versus @code{char * const}.  Because @code{char *} is encoded as
492 @code{*} and not as @code{^c}, there is no way to express the fact
493 that @code{r} applies to the pointer or to the pointee.
494
495 Hence, it is assumed as a convention that @code{r*} means @code{const
496 char *} (since it is what is most often meant), and there is no way to
497 encode @code{char *const}.  @code{char *const} would simply be encoded
498 as @code{*}, and the @code{const} is lost.
499
500 @menu
501 * Legacy type encoding::
502 * @@encode::
503 * Method signatures::
504 @end menu
505
506 @node Legacy type encoding
507 @subsection Legacy type encoding
508
509 Unfortunately, historically GCC used to have a number of bugs in its
510 encoding code.  The NeXT runtime expects GCC to emit type encodings in
511 this historical format (compatible with GCC-3.3), so when using the
512 NeXT runtime, GCC will introduce on purpose a number of incorrect
513 encodings:
514
515 @itemize @bullet
516
517 @item
518 the read-only qualifier of the pointee gets emitted before the '^'.
519 The read-only qualifier of the pointer itself gets ignored, unless it
520 is a typedef.  Also, the 'r' is only emitted for the outermost type.
521
522 @item
523 32-bit longs are encoded as 'l' or 'L', but not always.  For typedefs,
524 the compiler uses 'i' or 'I' instead if encoding a struct field or a
525 pointer.
526
527 @item
528 @code{enum}s are always encoded as 'i' (int) even if they are actually
529 unsigned or long.
530
531 @end itemize
532
533 In addition to that, the NeXT runtime uses a different encoding for
534 bitfields.  It encodes them as @code{b} followed by the size, without
535 a bit offset or the underlying field type.
536
537 @node @@encode
538 @subsection @@encode
539
540 GNU Objective-C supports the @code{@@encode} syntax that allows you to
541 create a type encoding from a C/Objective-C type.  For example,
542 @code{@@encode(int)} is compiled by the compiler into @code{"i"}.
543
544 @code{@@encode} does not support type qualifiers other than
545 @code{const}.  For example, @code{@@encode(const char*)} is valid and
546 is compiled into @code{"r*"}, while @code{@@encode(bycopy char *)} is
547 invalid and will cause a compilation error.
548
549 @node Method signatures
550 @subsection Method signatures
551
552 This section documents the encoding of method types, which is rarely
553 needed to use Objective-C.  You should skip it at a first reading; the
554 runtime provides functions that will work on methods and can walk
555 through the list of parameters and interpret them for you.  These
556 functions are part of the public ``API'' and are the preferred way to
557 interact with method signatures from user code.
558
559 But if you need to debug a problem with method signatures and need to
560 know how they are implemented (ie, the ``ABI''), read on.
561
562 Methods have their ``signature'' encoded and made available to the
563 runtime.  The ``signature'' encodes all the information required to
564 dynamically build invocations of the method at runtime: return type
565 and arguments.
566
567 The ``signature'' is a null-terminated string, composed of the following:
568
569 @itemize @bullet
570
571 @item
572 The return type, including type qualifiers.  For example, a method
573 returning @code{int} would have @code{i} here.
574
575 @item
576 The total size (in bytes) required to pass all the parameters.  This
577 includes the two hidden parameters (the object @code{self} and the
578 method selector @code{_cmd}).
579
580 @item
581 Each argument, with the type encoding, followed by the offset (in
582 bytes) of the argument in the list of parameters.
583
584 @end itemize
585
586 For example, a method with no arguments and returning @code{int} would
587 have the signature @code{i8@@0:4} if the size of a pointer is 4.  The
588 signature is interpreted as follows: the @code{i} is the return type
589 (an @code{int}), the @code{8} is the total size of the parameters in
590 bytes (two pointers each of size 4), the @code{@@0} is the first
591 parameter (an object at byte offset @code{0}) and @code{:4} is the
592 second parameter (a @code{SEL} at byte offset @code{4}).
593
594 You can easily find more examples by running the ``strings'' program
595 on an Objective-C object file compiled by GCC.  You'll see a lot of
596 strings that look very much like @code{i8@@0:4}.  They are signatures
597 of Objective-C methods.
598
599
600 @node Garbage Collection
601 @section Garbage Collection
602
603 This section is specific for the GNU Objective-C runtime.  If you are
604 using a different runtime, you can skip it.
605
606 Support for garbage collection with the GNU runtime has been added by
607 using a powerful conservative garbage collector, known as the
608 Boehm-Demers-Weiser conservative garbage collector.
609
610 To enable the support for it you have to configure the compiler using
611 an additional argument, @w{@option{--enable-objc-gc}}.  This will
612 build the boehm-gc library, and build an additional runtime library
613 which has several enhancements to support the garbage collector.  The
614 new library has a new name, @file{libobjc_gc.a} to not conflict with
615 the non-garbage-collected library.
616
617 When the garbage collector is used, the objects are allocated using the
618 so-called typed memory allocation mechanism available in the
619 Boehm-Demers-Weiser collector.  This mode requires precise information on
620 where pointers are located inside objects.  This information is computed
621 once per class, immediately after the class has been initialized.
622
623 There is a new runtime function @code{class_ivar_set_gcinvisible()}
624 which can be used to declare a so-called @dfn{weak pointer}
625 reference.  Such a pointer is basically hidden for the garbage collector;
626 this can be useful in certain situations, especially when you want to
627 keep track of the allocated objects, yet allow them to be
628 collected.  This kind of pointers can only be members of objects, you
629 cannot declare a global pointer as a weak reference.  Every type which is
630 a pointer type can be declared a weak pointer, including @code{id},
631 @code{Class} and @code{SEL}.
632
633 Here is an example of how to use this feature.  Suppose you want to
634 implement a class whose instances hold a weak pointer reference; the
635 following class does this:
636
637 @smallexample
638
639 @@interface WeakPointer : Object
640 @{
641     const void* weakPointer;
642 @}
643
644 - initWithPointer:(const void*)p;
645 - (const void*)weakPointer;
646 @@end
647
648
649 @@implementation WeakPointer
650
651 + (void)initialize
652 @{
653   class_ivar_set_gcinvisible (self, "weakPointer", YES);
654 @}
655
656 - initWithPointer:(const void*)p
657 @{
658   weakPointer = p;
659   return self;
660 @}
661
662 - (const void*)weakPointer
663 @{
664   return weakPointer;
665 @}
666
667 @@end
668
669 @end smallexample
670
671 Weak pointers are supported through a new type character specifier
672 represented by the @samp{!} character.  The
673 @code{class_ivar_set_gcinvisible()} function adds or removes this
674 specifier to the string type description of the instance variable named
675 as argument.
676
677 @c =========================================================================
678 @node Constant string objects
679 @section Constant string objects
680
681 GNU Objective-C provides constant string objects that are generated
682 directly by the compiler.  You declare a constant string object by
683 prefixing a C constant string with the character @samp{@@}:
684
685 @smallexample
686   id myString = @@"this is a constant string object";
687 @end smallexample
688
689 The constant string objects are by default instances of the
690 @code{NXConstantString} class which is provided by the GNU Objective-C
691 runtime.  To get the definition of this class you must include the
692 @file{objc/NXConstStr.h} header file.
693
694 User defined libraries may want to implement their own constant string
695 class.  To be able to support them, the GNU Objective-C compiler provides
696 a new command line options @option{-fconstant-string-class=@var{class-name}}.
697 The provided class should adhere to a strict structure, the same
698 as @code{NXConstantString}'s structure:
699
700 @smallexample
701
702 @@interface MyConstantStringClass
703 @{
704   Class isa;
705   char *c_string;
706   unsigned int len;
707 @}
708 @@end
709
710 @end smallexample
711
712 @code{NXConstantString} inherits from @code{Object}; user class
713 libraries may choose to inherit the customized constant string class
714 from a different class than @code{Object}.  There is no requirement in
715 the methods the constant string class has to implement, but the final
716 ivar layout of the class must be the compatible with the given
717 structure.
718
719 When the compiler creates the statically allocated constant string
720 object, the @code{c_string} field will be filled by the compiler with
721 the string; the @code{length} field will be filled by the compiler with
722 the string length; the @code{isa} pointer will be filled with
723 @code{NULL} by the compiler, and it will later be fixed up automatically
724 at runtime by the GNU Objective-C runtime library to point to the class
725 which was set by the @option{-fconstant-string-class} option when the
726 object file is loaded (if you wonder how it works behind the scenes, the
727 name of the class to use, and the list of static objects to fixup, are
728 stored by the compiler in the object file in a place where the GNU
729 runtime library will find them at runtime).
730
731 As a result, when a file is compiled with the
732 @option{-fconstant-string-class} option, all the constant string objects
733 will be instances of the class specified as argument to this option.  It
734 is possible to have multiple compilation units referring to different
735 constant string classes, neither the compiler nor the linker impose any
736 restrictions in doing this.
737
738 @c =========================================================================
739 @node compatibility_alias
740 @section compatibility_alias
741
742 The keyword @code{@@compatibility_alias} allows you to define a class name
743 as equivalent to another class name.  For example:
744
745 @smallexample
746 @@compatibility_alias WOApplication GSWApplication;
747 @end smallexample
748
749 tells the compiler that each time it encounters @code{WOApplication} as
750 a class name, it should replace it with @code{GSWApplication} (that is,
751 @code{WOApplication} is just an alias for @code{GSWApplication}).
752
753 There are some constraints on how this can be used---
754
755 @itemize @bullet
756
757 @item @code{WOApplication} (the alias) must not be an existing class;
758
759 @item @code{GSWApplication} (the real class) must be an existing class.
760
761 @end itemize
762
763 @c =========================================================================
764 @node Exceptions
765 @section Exceptions
766
767 GNU Objective-C provides exception support built into the language, as
768 in the following example:
769
770 @smallexample
771   @@try @{
772     @dots{}
773        @@throw expr;
774     @dots{}
775   @}
776   @@catch (AnObjCClass *exc) @{
777     @dots{}
778       @@throw expr;
779     @dots{}
780       @@throw;
781     @dots{}
782   @}
783   @@catch (AnotherClass *exc) @{
784     @dots{}
785   @}
786   @@catch (id allOthers) @{
787     @dots{}
788   @}
789   @@finally @{
790     @dots{}
791       @@throw expr;
792     @dots{}
793   @}
794 @end smallexample
795
796 The @code{@@throw} statement may appear anywhere in an Objective-C or
797 Objective-C++ program; when used inside of a @code{@@catch} block, the
798 @code{@@throw} may appear without an argument (as shown above), in
799 which case the object caught by the @code{@@catch} will be rethrown.
800
801 Note that only (pointers to) Objective-C objects may be thrown and
802 caught using this scheme.  When an object is thrown, it will be caught
803 by the nearest @code{@@catch} clause capable of handling objects of
804 that type, analogously to how @code{catch} blocks work in C++ and
805 Java.  A @code{@@catch(id @dots{})} clause (as shown above) may also
806 be provided to catch any and all Objective-C exceptions not caught by
807 previous @code{@@catch} clauses (if any).
808
809 The @code{@@finally} clause, if present, will be executed upon exit
810 from the immediately preceding @code{@@try @dots{} @@catch} section.
811 This will happen regardless of whether any exceptions are thrown,
812 caught or rethrown inside the @code{@@try @dots{} @@catch} section,
813 analogously to the behavior of the @code{finally} clause in Java.
814
815 There are several caveats to using the new exception mechanism:
816
817 @itemize @bullet
818 @item
819 The @option{-fobjc-exceptions} command line option must be used when
820 compiling Objective-C files that use exceptions.
821
822 @item
823 With the GNU runtime, exceptions are always implemented as ``native''
824 exceptions and it is recommended that the @option{-fexceptions} and
825 @option{-shared-libgcc} options are used when linking.
826
827 @item
828 With the NeXT runtime, although currently designed to be binary
829 compatible with @code{NS_HANDLER}-style idioms provided by the
830 @code{NSException} class, the new exceptions can only be used on Mac
831 OS X 10.3 (Panther) and later systems, due to additional functionality
832 needed in the NeXT Objective-C runtime.
833
834 @item
835 As mentioned above, the new exceptions do not support handling
836 types other than Objective-C objects.   Furthermore, when used from
837 Objective-C++, the Objective-C exception model does not interoperate with C++
838 exceptions at this time.  This means you cannot @code{@@throw} an exception
839 from Objective-C and @code{catch} it in C++, or vice versa
840 (i.e., @code{throw @dots{} @@catch}).
841 @end itemize
842
843 @c =========================================================================
844 @node Synchronization
845 @section Synchronization
846
847 GNU Objective-C provides support for synchronized blocks:
848
849 @smallexample
850   @@synchronized (ObjCClass *guard) @{
851     @dots{}
852   @}
853 @end smallexample
854
855 Upon entering the @code{@@synchronized} block, a thread of execution
856 shall first check whether a lock has been placed on the corresponding
857 @code{guard} object by another thread.  If it has, the current thread
858 shall wait until the other thread relinquishes its lock.  Once
859 @code{guard} becomes available, the current thread will place its own
860 lock on it, execute the code contained in the @code{@@synchronized}
861 block, and finally relinquish the lock (thereby making @code{guard}
862 available to other threads).
863
864 Unlike Java, Objective-C does not allow for entire methods to be
865 marked @code{@@synchronized}.  Note that throwing exceptions out of
866 @code{@@synchronized} blocks is allowed, and will cause the guarding
867 object to be unlocked properly.
868
869 Because of the interactions between synchronization and exception
870 handling, you can only use @code{@@synchronized} when compiling with
871 exceptions enabled, that is with the command line option
872 @option{-fobjc-exceptions}.
873
874
875 @c =========================================================================
876 @node Fast enumeration
877 @section Fast enumeration
878
879 @menu
880 * Using fast enumeration::
881 * c99-like fast enumeration syntax::
882 * Fast enumeration details::
883 * Fast enumeration protocol::
884 @end menu
885
886 @c ================================
887 @node Using fast enumeration
888 @subsection Using fast enumeration
889
890 GNU Objective-C provides support for the fast enumeration syntax:
891
892 @smallexample
893   id array = @dots{};
894   id object;
895
896   for (object in array)
897   @{
898     /* Do something with 'object' */
899   @}
900 @end smallexample
901
902 @code{array} needs to be an Objective-C object (usually a collection
903 object, for example an array, a dictionary or a set) which implements
904 the ``Fast Enumeration Protocol'' (see below).  If you are using a
905 Foundation library such as GNUstep Base or Apple Cocoa Foundation, all
906 collection objects in the library implement this protocol and can be
907 used in this way.
908
909 The code above would iterate over all objects in @code{array}.  For
910 each of them, it assigns it to @code{object}, then executes the
911 @code{Do something with 'object'} statements.
912
913 Here is a fully worked-out example using a Foundation library (which
914 provides the implementation of @code{NSArray}, @code{NSString} and
915 @code{NSLog}):
916
917 @smallexample
918   NSArray *array = [NSArray arrayWithObjects: @@"1", @@"2", @@"3", nil];
919   NSString *object;
920
921   for (object in array)
922     NSLog (@@"Iterating over %@@", object);
923 @end smallexample
924
925
926 @c ================================
927 @node c99-like fast enumeration syntax
928 @subsection c99-like fast enumeration syntax
929
930 A c99-like declaration syntax is also allowed:
931
932 @smallexample
933   id array = @dots{};
934
935   for (id object in array)
936   @{
937     /* Do something with 'object'  */
938   @}
939 @end smallexample
940
941 this is completely equivalent to:
942
943 @smallexample
944   id array = @dots{};
945
946   @{
947     id object;
948     for (object in array)
949     @{
950       /* Do something with 'object'  */
951     @}
952   @}
953 @end smallexample
954
955 but can save some typing.
956
957 Note that the option @option{-std=c99} is not required to allow this
958 syntax in Objective-C.
959
960 @c ================================
961 @node Fast enumeration details
962 @subsection Fast enumeration details
963
964 Here is a more technical description with the gory details.  Consider the code
965
966 @smallexample
967   for (@var{object expression} in @var{collection expression})
968   @{
969     @var{statements}
970   @}
971 @end smallexample
972
973 here is what happens when you run it:
974
975 @itemize @bullet
976 @item
977 @code{@var{collection expression}} is evaluated exactly once and the
978 result is used as the collection object to iterate over.  This means
979 it is safe to write code such as @code{for (object in [NSDictionary
980 keyEnumerator]) @dots{}}.
981
982 @item
983 the iteration is implemented by the compiler by repeatedly getting
984 batches of objects from the collection object using the fast
985 enumeration protocol (see below), then iterating over all objects in
986 the batch.  This is faster than a normal enumeration where objects are
987 retrieved one by one (hence the name ``fast enumeration'').
988
989 @item
990 if there are no objects in the collection, then
991 @code{@var{object expression}} is set to @code{nil} and the loop
992 immediately terminates.
993
994 @item
995 if there are objects in the collection, then for each object in the
996 collection (in the order they are returned) @code{@var{object expression}}
997 is set to the object, then @code{@var{statements}} are executed.
998
999 @item
1000 @code{@var{statements}} can contain @code{break} and @code{continue}
1001 commands, which will abort the iteration or skip to the next loop
1002 iteration as expected.
1003
1004 @item
1005 when the iteration ends because there are no more objects to iterate
1006 over, @code{@var{object expression}} is set to @code{nil}.  This allows
1007 you to determine whether the iteration finished because a @code{break}
1008 command was used (in which case @code{@var{object expression}} will remain
1009 set to the last object that was iterated over) or because it iterated
1010 over all the objects (in which case @code{@var{object expression}} will be
1011 set to @code{nil}).
1012
1013 @item
1014 @code{@var{statements}} must not make any changes to the collection
1015 object; if they do, it is a hard error and the fast enumeration
1016 terminates by invoking @code{objc_enumerationMutation}, a runtime
1017 function that normally aborts the program but which can be customized
1018 by Foundation libraries via @code{objc_set_mutation_handler} to do
1019 something different, such as raising an exception.
1020
1021 @end itemize
1022
1023 @c ================================
1024 @node Fast enumeration protocol
1025 @subsection Fast enumeration protocol
1026
1027 If you want your own collection object to be usable with fast
1028 enumeration, you need to have it implement the method
1029
1030 @smallexample
1031 - (unsigned long) countByEnumeratingWithState: (NSFastEnumerationState *)state 
1032                                       objects: (id *)objects
1033                                         count: (unsigneld long)len;
1034 @end smallexample
1035
1036 where @code{NSFastEnumerationState} must be defined in your code as follows:
1037
1038 @smallexample
1039 typdef struct
1040 @{
1041   unsigned long state;
1042   id            *itemsPtr;
1043   unsigned long *mutationsPtr;
1044   unsigned long extra[5];
1045 @} NSFastEnumerationState;
1046 @end smallexample
1047
1048 If no @code{NSFastEnumerationState} is defined in your code, the
1049 compiler will automatically replace @code{NSFastEnumerationState *}
1050 with @code{struct __objcFastEnumerationState *}, where that type is
1051 silently defined by the compiler in an identical way.  This can be
1052 confusing and we recommend that you define
1053 @code{NSFastEnumerationState} (as shown above) instead.
1054
1055 The method is called repeatedly during a fast enumeration to retrieve
1056 batches of objects.  Each invocation of the method should retrieve the
1057 next batch of objects.
1058
1059 The return value of the method is the number of objects in the current
1060 batch; this should not exceed @code{len}, which is the maximum size of
1061 a batch as requested by the caller.  The batch itself is returned in
1062 the @code{itemsPtr} field of the @code{NSFastEnumerationState} struct.
1063
1064 To help with returning the objects, the @code{objects} array is a C
1065 array preallocated by the caller (on the stack) of size @code{len}.
1066 In many cases you can put the objects you want to return in that
1067 @code{objects} array, then do @code{itemsPtr = objects}.  But you
1068 don't have to; if your collection already has the objects to return in
1069 some form of C array, it could return them from there instead.
1070
1071 The @code{state} and @code{extra} fields of the
1072 @code{NSFastEnumerationState} structure allows your collection object
1073 to keep track of the state of the enumeration.  In a simple array
1074 implementation, @code{state} may keep track of the index of the last
1075 object that was returned, and @code{extra} may be unused.
1076
1077 The @code{mutationsPtr} field of the @code{NSFastEnumerationState} is
1078 used to keep track of mutations.  It should point to a number; before
1079 working on each object, the fast enumeration loop will check that this
1080 number has not changed.  If it has, a mutation has happened and the
1081 fast enumeration will abort.  So, @code{mutationsPtr} could be set to
1082 point to some sort of version number of your collection, which is
1083 increased by one every time there is a change (for example when an
1084 object is added or removed).  Or, if you are content with less strict
1085 mutation checks, it could point to the number of objects in your
1086 collection or some other value that can be checked to perform an
1087 approximate check that the collection has not been mutated.
1088
1089 Finally, note how we declared the @code{len} argument and the return
1090 value to be of type @code{unsigned long}.  They could also be declared
1091 to be of type @code{unsigned int} and everything would still work.
1092
1093 @c =========================================================================
1094 @node Messaging with the GNU Objective-C runtime
1095 @section Messaging with the GNU Objective-C runtime
1096
1097 This section is specific for the GNU Objective-C runtime.  If you are
1098 using a different runtime, you can skip it.
1099
1100 The implementation of messaging in the GNU Objective-C runtime is
1101 designed to be portable, and so is based on standard C.
1102
1103 Sending a message in the GNU Objective-C runtime is composed of two
1104 separate steps.  First, there is a call to the lookup function,
1105 @code{objc_msg_lookup ()} (or, in the case of messages to super,
1106 @code{objc_msg_lookup_super ()}).  This runtime function takes as
1107 argument the receiver and the selector of the method to be called; it
1108 returns the @code{IMP}, that is a pointer to the function implementing
1109 the method.  The second step of method invocation consists of casting
1110 this pointer function to the appropriate function pointer type, and
1111 calling the function pointed to it with the right arguments.
1112
1113 For example, when the compiler encounters a method invocation such as
1114 @code{[object init]}, it compiles it into a call to
1115 @code{objc_msg_lookup (object, @@selector(init))} followed by a cast
1116 of the returned value to the appropriate function pointer type, and
1117 then it calls it.
1118
1119 @menu
1120 * Dynamically registering methods::
1121 * Forwarding hook::
1122 @end menu
1123
1124 @c =========================================================================
1125 @node Dynamically registering methods
1126 @subsection Dynamically registering methods
1127
1128 If @code{objc_msg_lookup()} does not find a suitable method
1129 implementation, because the receiver does not implement the required
1130 method, it tries to see if the class can dynamically register the
1131 method.
1132
1133 To do so, the runtime checks if the class of the receiver implements
1134 the method
1135
1136 @smallexample
1137 + (BOOL) resolveInstanceMethod: (SEL)selector;
1138 @end smallexample
1139
1140 in the case of an instance method, or 
1141
1142 @smallexample
1143 + (BOOL) resolveClassMethod: (SEL)selector;
1144 @end smallexample
1145
1146 in the case of a class method.  If the class implements it, the
1147 runtime invokes it, passing as argument the selector of the original
1148 method, and if it returns @code{YES}, the runtime tries the lookup
1149 again, which could now succeed if a matching method was added
1150 dynamically by @code{+resolveInstanceMethod:} or
1151 @code{+resolveClassMethod:}.
1152
1153 This allows classes to dynamically register methods (by adding them to
1154 the class using @code{class_addMethod}) when they are first called.
1155 To do so, a class should implement @code{+resolveInstanceMethod:} (or,
1156 depending on the case, @code{+resolveClassMethod:}) and have it
1157 recognize the selectors of methods that can be registered dynamically
1158 at runtime, register them, and return @code{YES}.  It should return
1159 @code{NO} for methods that it does not dynamically registered at
1160 runtime.
1161
1162 If @code{+resolveInstanceMethod:} (or @code{+resolveClassMethod:}) is
1163 not implemented or returns @code{NO}, the runtime then tries the
1164 forwarding hook.
1165
1166 Support for @code{+resolveInstanceMethod:} and
1167 @code{resolveClassMethod:} was added to the GNU Objective-C runtime in
1168 GCC version 4.6.
1169
1170 @c =========================================================================
1171 @node Forwarding hook
1172 @subsection Forwarding hook
1173
1174 The GNU Objective-C runtime provides a hook, called
1175 @code{__objc_msg_forward2}, which is called by
1176 @code{objc_msg_lookup()} when it can't find a method implementation in
1177 the runtime tables and after calling @code{+resolveInstanceMethod:}
1178 and @code{+resolveClassMethod:} has been attempted and did not succeed
1179 in dynamically registering the method.
1180
1181 To configure the hook, you set the global variable
1182 @code{__objc_msg_foward2} to a function with the same argument and
1183 return types of @code{objc_msg_lookup()}.  When
1184 @code{objc_msg_lookup()} can not find a method implementation, it
1185 invokes the hook function you provided to get a method implementation
1186 to return.  So, in practice @code{__objc_msg_forward2} allows you to
1187 extend @code{objc_msg_lookup()} by adding some custom code that is
1188 called to do a further lookup when no standard method implementation
1189 can be found using the normal lookup.
1190
1191 This hook is generally reserved for ``Foundation'' libraries such as
1192 GNUstep Base, which use it to implement their high-level method
1193 forwarding API, typically based around the @code{forwardInvocation:}
1194 method.  So, unless you are implementing your own ``Foundation''
1195 library, you should not set this hook.
1196
1197 In a typical forwarding implementation, the @code{__objc_msg_forward2}
1198 hook function determines the argument and return type of the method
1199 that is being looked up, and then creates a function that takes these
1200 arguments and has that return type, and returns it to the caller.
1201 Creating this function is non-trivial and is typically performed using
1202 a dedicated library such as @code{libffi}.
1203
1204 The forwarding method implementation thus created is returned by
1205 @code{objc_msg_lookup()} and is executed as if it was a normal method
1206 implementation.  When the forwarding method implementation is called,
1207 it is usually expected to pack all arguments into some sort of object
1208 (typically, an @code{NSInvocation} in a ``Foundation'' library), and
1209 hand it over to the programmer (@code{forwardInvocation:}) who is then
1210 allowed to manipulate the method invocation using a high-level API
1211 provided by the ``Foundation'' library.  For example, the programmer
1212 may want to examine the method invocation arguments and name and
1213 potentially change them before forwarding the method invocation to one
1214 or more local objects (@code{performInvocation:}) or even to remote
1215 objects (by using Distributed Objects or some other mechanism).  When
1216 all this completes, the return value is passed back and must be
1217 returned correctly to the original caller.
1218
1219 Note that the GNU Objective-C runtime currently provides no support
1220 for method forwarding or method invocations other than the
1221 @code{__objc_msg_forward2} hook.
1222
1223 If the forwarding hook does not exist or returns @code{NULL}, the
1224 runtime currently attempts forwarding using an older, deprecated API,
1225 and if that fails, it aborts the program.  In future versions of the
1226 GNU Objective-C runtime, the runtime will immediately abort.