blob: f7bbda365184a002d90b710d8300b977921a6355 [file] [log] [blame]
Chris Lattner7cfc8172009-03-09 07:01:20 +00001Language Specification for Blocks
2
32008/2/25 — created
42008/7/28 — revised, __block syntax
52008/8/13 — revised, Block globals
62008/8/21 — revised, C++ elaboration
72008/11/1 — revised, __weak support
82009/1/12 — revised, explicit return types
92009/2/10 — revised, __block objects need retain
10
11Copyright 2008-2009 Apple, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
12
13The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
14
15THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
16
17The Block Type
18
19A new derived type is introduced to C and, by extension, Objective-C, C++, and Objective-C++. Like function types, the Block type is a pair consisting of a result value type and a list of parameter types very similar to a function type. Blocks are intended to be used much like functions with the key distinction being that in addition to executable code they also contain various variable bindings to automatic (stack) or managed (heap) memory.
20
21The abstract declarator int (^)(char, float) describes a reference to a Block that, when invoked, takes two parameters, the first of type char and the second of type float, and returns a value of type int. The Block referenced is of opaque data that may reside in automatic (stack) memory, global memory, or heap memory.
22
23
24Block Variable Declarations
25
26A variable with Block type is declared using function pointer style notation substituting ^ for *. The following are valid Block variable declarations:
27 void (^blockReturningVoidWithVoidArgument)(void);
28 int (^blockReturningIntWithIntAndCharArguments)(int, char);
29 void (^arrayOfTenBlocksReturningVoidWithIntArgument[10])(int);
30
31Variadic ... arguments are supported. [variadic.c] A Block that takes no arguments must specify void in the argument list [voidarg.c]. An empty parameter list does not represent, as K&R provide, an unspecified argument list. Note: both gcc and clang support K&R style as a convenience.
32
33A Block reference may be cast to a pointer of arbitrary type and vice versa. [cast.c] A Block reference may not be dereferenced via the pointer dereference operator *, and thus a Block's size may not be computed at compile time. [sizeof.c]
34
35
36Block Literal Expressions
37
38A Block literal expression produces a reference to a Block. It is introduced by the use of the ^ token as a unary operator.
39 Block_literal_expression ::= ^ block_decl compound_statement_body
40 block_decl ::=
41 block_decl ::= parameter_list
42 block_decl ::= type_expression
43
44...where type expression is extended to allow ^ as a Block reference (pointer) where * is allowed as a function reference (pointer).
45
46The following Block literal:
47 ^ void (void) { printf("hello world\n"); }
48
49...produces a reference to a Block with no arguments with no return value.
50
51The return type is optional and is inferred from the return statements. If the return statements return a value, they all must return a value of the same type. If there is no value returned the inferred type of the Block is void; otherwise it is the type of the return statement value.
52
53If the return type is omitted and the argument list is ( void ), the ( void ) argument list may also be omitted.
54
55So:
56 ^ ( void ) { printf("hello world\n"); }
57
58...and:
59 ^ { printf("hello world\n"); }
60
61...are exactly equivalent constructs for the same expression.
62
63The type_expression extends C expression parsing to accommodate Block reference declarations as it accommodates function pointer declarations.
64
65Given:
66 typedef int (*pointerToFunctionThatReturnsIntWithCharArg)(char);
67 pointerToFunctionThatReturnsIntWithCharArg functionPointer;
68
69 ^ pointerToFunctionThatReturnsIntWithCharArg (float x) { return functionPointer; }
70
71...and:
72 ^ int ((*)(float x))(char) { return functionPointer; }
73
74...are equivalent expressions, as is:
75
76 ^(float x) { return functionPointer; }
77
78[returnfunctionptr.c]
79
80The compound statement body establishes a new lexical scope within that of its parent. Variables used within the scope of the compound statement are bound to the Block in the normal manner with the exception of those in automatic (stack) storage. Thus one may access functions and global variables as one would expect, as well as static local variables. [testme]
81
82Local automatic (stack) variables referenced within the compound statement of a Block are imported and captured by the Block as const copies. The capture (binding) is performed at the time of the Block literal expression evaluation.
83
84The lifetime of variables declared in a Block is that of a function; each activation frame contains a new copy of variables declared within the local scope of the Block. Such variable declarations should be allowed anywhere [testme] rather than only when C99 parsing is requested, including for statements. [testme]
85
86Block literal expressions may occur within Block literal expressions (nest) and all variables captured by any nested blocks are implicitly also captured in the scopes of their enclosing Blocks.
87
88A Block literal expression may be used as the initialization value for Block variables at global or local static scope.
89
90
91The Invoke Operator
92
93Blocks are invoked using function call syntax with a list of expression parameters of types corresponding to the declaration and returning a result type also according to the declaration. Given:
94 int (^x)(char);
95 void (^z)(void);
96 int (^(*y))(char) = &x;
97
98...the following are all legal Block invocations:
99 x('a');
100 (*y)('a');
101 (true ? x : *y)('a')
102
103
104The Copy and Release Operations
105
106The compiler and runtime provide copy and release operations for Block references that create and, in matched use, release allocated storage for referenced Blocks.
107
108The copy operation Block_copy() is styled as a function that takes an arbitrary Block reference and returns a Block reference of the same type. The release operation, Block_release(), is styled as a function that takes an arbitrary Block reference and, if dynamically matched to a Block copy operation, allows recovery of the referenced allocated memory.
109
110
111The __block Storage Qualifier
112
113In addition to the new Block type we also introduce a new storage qualifier, __block, for local variables. [testme: a __block declaration within a block literal] The __block storage qualifier is mutually exclusive to the existing local storage qualifiers auto, register, and static.[testme] Variables qualified by __block act as if they were in allocated storage and this storage is automatically recovered after last use of said variable. An implementation may choose an optimization where the storage is initially automatic and only "moved" to allocated (heap) storage upon a Block_copy of a referencing Block. Such variables may be mutated as normal variables are.
114
115In the case where a __block variable is a Block one must assume that the __block variable resides in allocated storage and as such is assumed to reference a Block that is also in allocated storage (that it is the result of a Block_copy operation). Despite this there is no provision to do a Block_copy or a Block_release if an implementation provides initial automatic storage for Blocks. This is due to the inherent race condition of potentially several threads trying to update the shared variable and the need for synchronization around disposing of older values and copying new ones. Such synchronization is beyond the scope of this language specification.
116
117
118Control Flow
119
120The compound statement of a Block is treated much like a function body with respect to control flow in that goto, break, and continue do not escape the Block. Exceptions are treated "normally" in that when thrown they pop stack frames until a catch clause is found.
121
122
123Objective-C Extensions
124
125Objective-C extends the definition of a Block reference type to be that also of id. A variable or expression of Block type may be messaged or used as a parameter wherever an id may be. The converse is also true. Block references may thus appear as properties and are subject to the assign, retain, and copy attribute logic that is reserved for objects.
126
127All Blocks are constructed to be Objective-C objects regardless of whether the Objective-C runtime is operational in the program or not. Blocks using automatic (stack) memory are objects and may be messaged, although they may not be assigned into __weak locations if garbage collection is enabled.
128
129Within a Block literal expression within a method definition references to instance variables are also imported into the lexical scope of the compound statement. These variables are implicitly qualified as references from self, and so self is imported as a const copy. The net effect is that instance variables can be mutated.
130
131The Block_copy operator retains all objects held in variables of automatic storage referenced within the Block expression (or form strong references if running under garbage collection). Object variables of __block storage type are assumed to hold normal pointers with no provision for retain and release messages.
132
133Foundation defines (and supplies) -copy and -release methods for Blocks.
134
135In the Objective-C and Objective-C++ languages, we allow the __weak specifier for __block variables of object type. If garbage collection is not enabled, this qualifier causes these variables to be kept without retain messages being sent. This knowingly leads to dangling pointers if the Block (or a copy) outlives the lifetime of this object.
136
137In garbage collected environments, the __weak variable is set to nil when the object it references is collected, as long as the __block variable resides in the heap (either by default or via Block_copy()). The initial Apple implementation does in fact start __block variables on the stack and migrate them to the heap only as a result of a Block_copy() operation.
138
139It is a runtime error to attempt to assign a reference to a stack-based Block into any storage marked __weak, including __weak __block variables.
140
141
142C++ Extensions
143
144Block literal expressions within functions are extended to allow const use of C++ objects, pointers, or references held in automatic storage.
145
146For example, given class Foo with member function fighter(void):
147 Foo foo;
148 Foo &fooRef = foo;
149 Foo *fooPtr = &foo;
150
151...a Block that used foo would import the variables as const variations:
152 const Foo block_foo = foo; // const copy constructor
153 const Foo &block_fooRef = fooRef;
Blaine Garstc31e0162011-06-14 21:41:00 +0000154 Foo *const block_fooPtr = fooPtr;
Chris Lattner7cfc8172009-03-09 07:01:20 +0000155
156Stack-local objects are copied into a Block via a copy const constructor. If no such constructor exists, it is considered an error to reference such objects from within the Block compound statements. A destructor is run as control leaves the compound statement that contains the Block literal expression.
157
158If a Block originates on the stack, a const copy constructor of the stack-based Block const copy is performed when a Block_copy operation is called; when the last Block_release (or subsequently GC) occurs, a destructor is run on the heap copy.
159
160Variables declared as residing in __block storage may be initially allocated in the heap or may first appear on the stack and be copied to the heap as a result of a Block_copy() operation. When copied from the stack, a normal copy constructor is used to initialize the heap-based version from the original stack version. The destructor for a const copied object is run at the normal end of scope. The destructor for any initial stack based version is also called at normal end of scope.
161
162Within a member function, access to member functions and variables is done via an implicit const copy of a this pointer.
163
164Member variables that are Blocks may not be overloaded by the types of their arguments.
165