362 lines · plain
1 2.. role:: block-term3 4=================================5Language Specification for Blocks6=================================7 8.. contents::9 :local:10 11Revisions12=========13 14- 2008/2/25 --- created15- 2008/7/28 --- revised, ``__block`` syntax16- 2008/8/13 --- revised, Block globals17- 2008/8/21 --- revised, C++ elaboration18- 2008/11/1 --- revised, ``__weak`` support19- 2009/1/12 --- revised, explicit return types20- 2009/2/10 --- revised, ``__block`` objects need retain21 22Overview23========24 25A new derived type is introduced to C and, by extension, Objective-C,26C++, and Objective-C++27 28The Block Type29==============30 31Like function types, the :block-term:`Block type` is a pair consisting32of a result value type and a list of parameter types very similar to a33function type. Blocks are intended to be used much like functions with34the key distinction being that in addition to executable code they35also contain various variable bindings to automatic (stack) or managed36(heap) memory.37 38The abstract declarator,39 40.. code-block:: c41 42 int (^)(char, float)43 44describes a reference to a Block that, when invoked, takes two45parameters, the first of type char and the second of type float, and46returns a value of type int. The Block referenced is of opaque data47that may reside in automatic (stack) memory, global memory, or heap48memory.49 50Block Variable Declarations51===========================52 53A :block-term:`variable with Block type` is declared using function54pointer style notation substituting ``^`` for ``*``. The following are55valid Block variable declarations:56 57.. code-block:: c58 59 void (^blockReturningVoidWithVoidArgument)(void);60 int (^blockReturningIntWithIntAndCharArguments)(int, char);61 void (^arrayOfTenBlocksReturningVoidWithIntArgument[10])(int);62 63Variadic ``...`` arguments are supported. [variadic.c] A Block that64takes no arguments must specify void in the argument list [voidarg.c].65An empty parameter list does not represent, as K&R provide, an66unspecified argument list. Note: both gcc and clang support K&R style67as a convenience.68 69A Block reference may be cast to a pointer of arbitrary type and vice70versa. [cast.c] A Block reference may not be dereferenced via the71pointer dereference operator ``*``, and thus a Block's size may not be72computed at compile time. [sizeof.c]73 74Block Literal Expressions75=========================76 77A :block-term:`Block literal expression` produces a reference to a78Block. It is introduced by the use of the ``^`` token as a unary79operator.80 81.. code-block:: c82 83 Block_literal_expression ::= ^ block_decl compound_statement_body84 block_decl ::=85 block_decl ::= parameter_list86 block_decl ::= type_expression87 88where type expression is extended to allow ``^`` as a Block reference89(pointer) where ``*`` is allowed as a function reference (pointer).90 91The following Block literal:92 93.. code-block:: c94 95 ^ void (void) { printf("hello world\n"); }96 97produces a reference to a Block with no arguments with no return value.98 99The return type is optional and is inferred from the return100statements. If the return statements return a value, they all must101return a value of the same type. If there is no value returned the102inferred type of the Block is void; otherwise it is the type of the103return statement value.104 105If the return type is omitted and the argument list is ``( void )``,106the ``( void )`` argument list may also be omitted.107 108So:109 110.. code-block:: c111 112 ^ ( void ) { printf("hello world\n"); }113 114and:115 116.. code-block:: c117 118 ^ { printf("hello world\n"); }119 120are exactly equivalent constructs for the same expression.121 122The type_expression extends C expression parsing to accommodate Block123reference declarations as it accommodates function pointer124declarations.125 126Given:127 128.. code-block:: c129 130 typedef int (*pointerToFunctionThatReturnsIntWithCharArg)(char);131 pointerToFunctionThatReturnsIntWithCharArg functionPointer;132 ^ pointerToFunctionThatReturnsIntWithCharArg (float x) { return functionPointer; }133 134and:135 136.. code-block:: c137 138 ^ int ((*)(float x))(char) { return functionPointer; }139 140are equivalent expressions, as is:141 142.. code-block:: c143 144 ^(float x) { return functionPointer; }145 146[returnfunctionptr.c]147 148The compound statement body establishes a new lexical scope within149that of its parent. Variables used within the scope of the compound150statement are bound to the Block in the normal manner with the151exception of those in automatic (stack) storage. Thus one may access152functions and global variables as one would expect, as well as static153local variables. [testme]154 155Local automatic (stack) variables referenced within the compound156statement of a Block are imported and captured by the Block as const157copies. The capture (binding) is performed at the time of the Block158literal expression evaluation.159 160The compiler is not required to capture a variable if it can prove161that no references to the variable will actually be evaluated.162Programmers can force a variable to be captured by referencing it in a163statement at the beginning of the Block, like so:164 165.. code-block:: c166 167 (void) foo;168 169This matters when capturing the variable has side-effects, as it can170in Objective-C or C++.171 172The lifetime of variables declared in a Block is that of a function;173each activation frame contains a new copy of variables declared within174the local scope of the Block. Such variable declarations should be175allowed anywhere [testme] rather than only when C99 parsing is176requested, including for statements. [testme]177 178Block literal expressions may occur within Block literal expressions179(nest) and all variables captured by any nested blocks are implicitly180also captured in the scopes of their enclosing Blocks.181 182A Block literal expression may be used as the initialization value for183Block variables at global or local static scope.184 185The Invoke Operator186===================187 188Blocks are :block-term:`invoked` using function call syntax with a189list of expression parameters of types corresponding to the190declaration and returning a result type also according to the191declaration. Given:192 193.. code-block:: c194 195 int (^x)(char);196 void (^z)(void);197 int (^(*y))(char) = &x;198 199the following are all legal Block invocations:200 201.. code-block:: c202 203 x('a');204 (*y)('a');205 (true ? x : *y)('a')206 207The Copy and Release Operations208===============================209 210The compiler and runtime provide :block-term:`copy` and211:block-term:`release` operations for Block references that create and,212in matched use, release allocated storage for referenced Blocks.213 214The copy operation ``Block_copy()`` is styled as a function that takes215an arbitrary Block reference and returns a Block reference of the same216type. The release operation, ``Block_release()``, is styled as a217function that takes an arbitrary Block reference and, if dynamically218matched to a Block copy operation, allows recovery of the referenced219allocated memory.220 221 222The ``__block`` Storage Qualifier223=================================224 225In addition to the new Block type we also introduce a new storage226qualifier, :block-term:`__block`, for local variables. [testme: a227__block declaration within a block literal] The ``__block`` storage228qualifier is mutually exclusive to the existing local storage229qualifiers auto, register, and static. [testme] Variables qualified by230``__block`` act as if they were in allocated storage and this storage231is automatically recovered after last use of said variable. An232implementation may choose an optimization where the storage is233initially automatic and only "moved" to allocated (heap) storage upon234a Block_copy of a referencing Block. Such variables may be mutated as235normal variables are.236 237In the case where a ``__block`` variable is a Block one must assume238that the ``__block`` variable resides in allocated storage and as such239is assumed to reference a Block that is also in allocated storage240(that it is the result of a ``Block_copy`` operation). Despite this241there is no provision to do a ``Block_copy`` or a ``Block_release`` if242an implementation provides initial automatic storage for Blocks. This243is due to the inherent race condition of potentially several threads244trying to update the shared variable and the need for synchronization245around disposing of older values and copying new ones. Such246synchronization is beyond the scope of this language specification.247 248 249Control Flow250============251 252The compound statement of a Block is treated much like a function body253with respect to control flow in that goto, break, and continue do not254escape the Block. Exceptions are treated *normally* in that when255thrown they pop stack frames until a catch clause is found.256 257 258Objective-C Extensions259======================260 261Objective-C extends the definition of a Block reference type to be262that also of id. A variable or expression of Block type may be263messaged or used as a parameter wherever an id may be. The converse is264also true. Block references may thus appear as properties and are265subject to the assign, retain, and copy attribute logic that is266reserved for objects.267 268All Blocks are constructed to be Objective-C objects regardless of269whether the Objective-C runtime is operational in the program or270not. Blocks using automatic (stack) memory are objects and may be271messaged, although they may not be assigned into ``__weak`` locations272if garbage collection is enabled.273 274Within a Block literal expression within a method definition275references to instance variables are also imported into the lexical276scope of the compound statement. These variables are implicitly277qualified as references from self, and so self is imported as a const278copy. The net effect is that instance variables can be mutated.279 280The :block-term:`Block_copy` operator retains all objects held in281variables of automatic storage referenced within the Block expression282(or forms strong references if running under garbage collection).283Object variables of ``__block`` storage type are assumed to hold284normal pointers with no provision for retain and release messages.285 286Foundation defines (and supplies) ``-copy`` and ``-release`` methods for287Blocks.288 289In the Objective-C and Objective-C++ languages, we allow the290``__weak`` specifier for ``__block`` variables of object type. If291garbage collection is not enabled, this qualifier causes these292variables to be kept without retain messages being sent. This293knowingly leads to dangling pointers if the Block (or a copy) outlives294the lifetime of this object.295 296In garbage collected environments, the ``__weak`` variable is set to297nil when the object it references is collected, as long as the298``__block`` variable resides in the heap (either by default or via299``Block_copy()``). The initial Apple implementation does in fact300start ``__block`` variables on the stack and migrate them to the heap301only as a result of a ``Block_copy()`` operation.302 303It is a runtime error to attempt to assign a reference to a304stack-based Block into any storage marked ``__weak``, including305``__weak`` ``__block`` variables.306 307 308C++ Extensions309==============310 311Block literal expressions within functions are extended to allow const312use of C++ objects, pointers, or references held in automatic storage.313 314As usual, within the block, references to captured variables become315const-qualified, as if they were references to members of a const316object. Note that this does not change the type of a variable of317reference type.318 319For example, given a class Foo:320 321.. code-block:: c322 323 Foo foo;324 Foo &fooRef = foo;325 Foo *fooPtr = &foo;326 327A Block that referenced these variables would import the variables as328const variations:329 330.. code-block:: c331 332 const Foo block_foo = foo;333 Foo &block_fooRef = fooRef;334 Foo *const block_fooPtr = fooPtr;335 336Captured variables are copied into the Block at the instant of337evaluating the Block literal expression. They are also copied when338calling ``Block_copy()`` on a Block allocated on the stack. In both339cases, they are copied as if the variable were const-qualified, and340it's an error if there's no such constructor.341 342Captured variables in Blocks on the stack are destroyed when control343leaves the compound statement that contains the Block literal344expression. Captured variables in Blocks on the heap are destroyed345when the reference count of the Block drops to zero.346 347Variables declared as residing in ``__block`` storage may be initially348allocated in the heap or may first appear on the stack and be copied349to the heap as a result of a ``Block_copy()`` operation. When copied350from the stack, ``__block`` variables are copied using their normal351qualification (i.e. without adding const). In C++11, ``__block``352variables are copied as x-values if that is possible, then as l-values353if not; if both fail, it's an error. The destructor for any initial354stack-based version is called at the variable's normal end of scope.355 356References to ``this``, as well as references to non-static members of357any enclosing class, are evaluated by capturing ``this`` just like a358normal variable of C pointer type.359 360Member variables that are Blocks may not be overloaded by the types of361their arguments.362