BlockLanguageSpec.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. .. role:: block-term
  2. =================================
  3. Language Specification for Blocks
  4. =================================
  5. .. contents::
  6. :local:
  7. Revisions
  8. =========
  9. - 2008/2/25 --- created
  10. - 2008/7/28 --- revised, ``__block`` syntax
  11. - 2008/8/13 --- revised, Block globals
  12. - 2008/8/21 --- revised, C++ elaboration
  13. - 2008/11/1 --- revised, ``__weak`` support
  14. - 2009/1/12 --- revised, explicit return types
  15. - 2009/2/10 --- revised, ``__block`` objects need retain
  16. Overview
  17. ========
  18. A new derived type is introduced to C and, by extension, Objective-C,
  19. C++, and Objective-C++
  20. The Block Type
  21. ==============
  22. Like function types, the :block-term:`Block type` is a pair consisting
  23. of a result value type and a list of parameter types very similar to a
  24. function type. Blocks are intended to be used much like functions with
  25. the key distinction being that in addition to executable code they
  26. also contain various variable bindings to automatic (stack) or managed
  27. (heap) memory.
  28. The abstract declarator,
  29. .. code-block:: c
  30. int (^)(char, float)
  31. describes a reference to a Block that, when invoked, takes two
  32. parameters, the first of type char and the second of type float, and
  33. returns a value of type int. The Block referenced is of opaque data
  34. that may reside in automatic (stack) memory, global memory, or heap
  35. memory.
  36. Block Variable Declarations
  37. ===========================
  38. A :block-term:`variable with Block type` is declared using function
  39. pointer style notation substituting ``^`` for ``*``. The following are
  40. valid Block variable declarations:
  41. .. code-block:: c
  42. void (^blockReturningVoidWithVoidArgument)(void);
  43. int (^blockReturningIntWithIntAndCharArguments)(int, char);
  44. void (^arrayOfTenBlocksReturningVoidWithIntArgument[10])(int);
  45. Variadic ``...`` arguments are supported. [variadic.c] A Block that
  46. takes no arguments must specify void in the argument list [voidarg.c].
  47. An empty parameter list does not represent, as K&R provide, an
  48. unspecified argument list. Note: both gcc and clang support K&R style
  49. as a convenience.
  50. A Block reference may be cast to a pointer of arbitrary type and vice
  51. versa. [cast.c] A Block reference may not be dereferenced via the
  52. pointer dereference operator ``*``, and thus a Block's size may not be
  53. computed at compile time. [sizeof.c]
  54. Block Literal Expressions
  55. =========================
  56. A :block-term:`Block literal expression` produces a reference to a
  57. Block. It is introduced by the use of the ``^`` token as a unary
  58. operator.
  59. .. code-block:: c
  60. Block_literal_expression ::= ^ block_decl compound_statement_body
  61. block_decl ::=
  62. block_decl ::= parameter_list
  63. block_decl ::= type_expression
  64. where type expression is extended to allow ``^`` as a Block reference
  65. (pointer) where ``*`` is allowed as a function reference (pointer).
  66. The following Block literal:
  67. .. code-block:: c
  68. ^ void (void) { printf("hello world\n"); }
  69. produces a reference to a Block with no arguments with no return value.
  70. The return type is optional and is inferred from the return
  71. statements. If the return statements return a value, they all must
  72. return a value of the same type. If there is no value returned the
  73. inferred type of the Block is void; otherwise it is the type of the
  74. return statement value.
  75. If the return type is omitted and the argument list is ``( void )``,
  76. the ``( void )`` argument list may also be omitted.
  77. So:
  78. .. code-block:: c
  79. ^ ( void ) { printf("hello world\n"); }
  80. and:
  81. .. code-block:: c
  82. ^ { printf("hello world\n"); }
  83. are exactly equivalent constructs for the same expression.
  84. The type_expression extends C expression parsing to accommodate Block
  85. reference declarations as it accommodates function pointer
  86. declarations.
  87. Given:
  88. .. code-block:: c
  89. typedef int (*pointerToFunctionThatReturnsIntWithCharArg)(char);
  90. pointerToFunctionThatReturnsIntWithCharArg functionPointer;
  91. ^ pointerToFunctionThatReturnsIntWithCharArg (float x) { return functionPointer; }
  92. and:
  93. .. code-block:: c
  94. ^ int ((*)(float x))(char) { return functionPointer; }
  95. are equivalent expressions, as is:
  96. .. code-block:: c
  97. ^(float x) { return functionPointer; }
  98. [returnfunctionptr.c]
  99. The compound statement body establishes a new lexical scope within
  100. that of its parent. Variables used within the scope of the compound
  101. statement are bound to the Block in the normal manner with the
  102. exception of those in automatic (stack) storage. Thus one may access
  103. functions and global variables as one would expect, as well as static
  104. local variables. [testme]
  105. Local automatic (stack) variables referenced within the compound
  106. statement of a Block are imported and captured by the Block as const
  107. copies. The capture (binding) is performed at the time of the Block
  108. literal expression evaluation.
  109. The compiler is not required to capture a variable if it can prove
  110. that no references to the variable will actually be evaluated.
  111. Programmers can force a variable to be captured by referencing it in a
  112. statement at the beginning of the Block, like so:
  113. .. code-block:: c
  114. (void) foo;
  115. This matters when capturing the variable has side-effects, as it can
  116. in Objective-C or C++.
  117. The lifetime of variables declared in a Block is that of a function;
  118. each activation frame contains a new copy of variables declared within
  119. the local scope of the Block. Such variable declarations should be
  120. allowed anywhere [testme] rather than only when C99 parsing is
  121. requested, including for statements. [testme]
  122. Block literal expressions may occur within Block literal expressions
  123. (nest) and all variables captured by any nested blocks are implicitly
  124. also captured in the scopes of their enclosing Blocks.
  125. A Block literal expression may be used as the initialization value for
  126. Block variables at global or local static scope.
  127. The Invoke Operator
  128. ===================
  129. Blocks are :block-term:`invoked` using function call syntax with a
  130. list of expression parameters of types corresponding to the
  131. declaration and returning a result type also according to the
  132. declaration. Given:
  133. .. code-block:: c
  134. int (^x)(char);
  135. void (^z)(void);
  136. int (^(*y))(char) = &x;
  137. the following are all legal Block invocations:
  138. .. code-block:: c
  139. x('a');
  140. (*y)('a');
  141. (true ? x : *y)('a')
  142. The Copy and Release Operations
  143. ===============================
  144. The compiler and runtime provide :block-term:`copy` and
  145. :block-term:`release` operations for Block references that create and,
  146. in matched use, release allocated storage for referenced Blocks.
  147. The copy operation ``Block_copy()`` is styled as a function that takes
  148. an arbitrary Block reference and returns a Block reference of the same
  149. type. The release operation, ``Block_release()``, is styled as a
  150. function that takes an arbitrary Block reference and, if dynamically
  151. matched to a Block copy operation, allows recovery of the referenced
  152. allocated memory.
  153. The ``__block`` Storage Qualifier
  154. =================================
  155. In addition to the new Block type we also introduce a new storage
  156. qualifier, :block-term:`__block`, for local variables. [testme: a
  157. __block declaration within a block literal] The ``__block`` storage
  158. qualifier is mutually exclusive to the existing local storage
  159. qualifiers auto, register, and static. [testme] Variables qualified by
  160. ``__block`` act as if they were in allocated storage and this storage
  161. is automatically recovered after last use of said variable. An
  162. implementation may choose an optimization where the storage is
  163. initially automatic and only "moved" to allocated (heap) storage upon
  164. a Block_copy of a referencing Block. Such variables may be mutated as
  165. normal variables are.
  166. In the case where a ``__block`` variable is a Block one must assume
  167. that the ``__block`` variable resides in allocated storage and as such
  168. is assumed to reference a Block that is also in allocated storage
  169. (that it is the result of a ``Block_copy`` operation). Despite this
  170. there is no provision to do a ``Block_copy`` or a ``Block_release`` if
  171. an implementation provides initial automatic storage for Blocks. This
  172. is due to the inherent race condition of potentially several threads
  173. trying to update the shared variable and the need for synchronization
  174. around disposing of older values and copying new ones. Such
  175. synchronization is beyond the scope of this language specification.
  176. Control Flow
  177. ============
  178. The compound statement of a Block is treated much like a function body
  179. with respect to control flow in that goto, break, and continue do not
  180. escape the Block. Exceptions are treated *normally* in that when
  181. thrown they pop stack frames until a catch clause is found.
  182. Objective-C Extensions
  183. ======================
  184. Objective-C extends the definition of a Block reference type to be
  185. that also of id. A variable or expression of Block type may be
  186. messaged or used as a parameter wherever an id may be. The converse is
  187. also true. Block references may thus appear as properties and are
  188. subject to the assign, retain, and copy attribute logic that is
  189. reserved for objects.
  190. All Blocks are constructed to be Objective-C objects regardless of
  191. whether the Objective-C runtime is operational in the program or
  192. not. Blocks using automatic (stack) memory are objects and may be
  193. messaged, although they may not be assigned into ``__weak`` locations
  194. if garbage collection is enabled.
  195. Within a Block literal expression within a method definition
  196. references to instance variables are also imported into the lexical
  197. scope of the compound statement. These variables are implicitly
  198. qualified as references from self, and so self is imported as a const
  199. copy. The net effect is that instance variables can be mutated.
  200. The :block-term:`Block_copy` operator retains all objects held in
  201. variables of automatic storage referenced within the Block expression
  202. (or form strong references if running under garbage collection).
  203. Object variables of ``__block`` storage type are assumed to hold
  204. normal pointers with no provision for retain and release messages.
  205. Foundation defines (and supplies) ``-copy`` and ``-release`` methods for
  206. Blocks.
  207. In the Objective-C and Objective-C++ languages, we allow the
  208. ``__weak`` specifier for ``__block`` variables of object type. If
  209. garbage collection is not enabled, this qualifier causes these
  210. variables to be kept without retain messages being sent. This
  211. knowingly leads to dangling pointers if the Block (or a copy) outlives
  212. the lifetime of this object.
  213. In garbage collected environments, the ``__weak`` variable is set to
  214. nil when the object it references is collected, as long as the
  215. ``__block`` variable resides in the heap (either by default or via
  216. ``Block_copy()``). The initial Apple implementation does in fact
  217. start ``__block`` variables on the stack and migrate them to the heap
  218. only as a result of a ``Block_copy()`` operation.
  219. It is a runtime error to attempt to assign a reference to a
  220. stack-based Block into any storage marked ``__weak``, including
  221. ``__weak`` ``__block`` variables.
  222. C++ Extensions
  223. ==============
  224. Block literal expressions within functions are extended to allow const
  225. use of C++ objects, pointers, or references held in automatic storage.
  226. As usual, within the block, references to captured variables become
  227. const-qualified, as if they were references to members of a const
  228. object. Note that this does not change the type of a variable of
  229. reference type.
  230. For example, given a class Foo:
  231. .. code-block:: c
  232. Foo foo;
  233. Foo &fooRef = foo;
  234. Foo *fooPtr = &foo;
  235. A Block that referenced these variables would import the variables as
  236. const variations:
  237. .. code-block:: c
  238. const Foo block_foo = foo;
  239. Foo &block_fooRef = fooRef;
  240. Foo *const block_fooPtr = fooPtr;
  241. Captured variables are copied into the Block at the instant of
  242. evaluating the Block literal expression. They are also copied when
  243. calling ``Block_copy()`` on a Block allocated on the stack. In both
  244. cases, they are copied as if the variable were const-qualified, and
  245. it's an error if there's no such constructor.
  246. Captured variables in Blocks on the stack are destroyed when control
  247. leaves the compound statement that contains the Block literal
  248. expression. Captured variables in Blocks on the heap are destroyed
  249. when the reference count of the Block drops to zero.
  250. Variables declared as residing in ``__block`` storage may be initially
  251. allocated in the heap or may first appear on the stack and be copied
  252. to the heap as a result of a ``Block_copy()`` operation. When copied
  253. from the stack, ``__block`` variables are copied using their normal
  254. qualification (i.e. without adding const). In C++11, ``__block``
  255. variables are copied as x-values if that is possible, then as l-values
  256. if not; if both fail, it's an error. The destructor for any initial
  257. stack-based version is called at the variable's normal end of scope.
  258. References to ``this``, as well as references to non-static members of
  259. any enclosing class, are evaluated by capturing ``this`` just like a
  260. normal variable of C pointer type.
  261. Member variables that are Blocks may not be overloaded by the types of
  262. their arguments.