blob: 63b523c6dfcdecf38ed585aa551aa3f42e9c3f6b [file] [log] [blame]
Patrick Beardaf39ba12012-03-20 20:50:45 +00001<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
3<!-- Material used from: HTML 4.01 specs: http://www.w3.org/TR/html401/ -->
4<html>
5<head>
6 <META http-equiv="Content-Type" content="text/html; charset=UTF8">
7 <title>Clang Language Extensions</title>
8 <link type="text/css" rel="stylesheet" href="../menu.css">
9 <link type="text/css" rel="stylesheet" href="../content.css">
10 <style type="text/css">
11 td {
12 vertical-align: top;
13 }
14 th { background-color: #ffddaa; }
15 </style>
16</head>
17<body>
18
19<!--#include virtual="../menu.html.incl"-->
20
21<div id="content">
22
23<h1>Objective-C Literals</h1>
24
25<h2>Introduction</h2>
26
27Three new features were introduced into clang at the same time: <i>NSNumber Literals</i> provide a syntax for creating <code>NSNumber</code> from scalar literal expressions; <i>Collection Literals</i> provide a short-hand for creating arrays and dictionaries; <i>Object Subscripting</i> provides a way to use subscripting with Objective-C objects. Users of Apple compiler releases can use these features starting with the Apple LLVM Compiler 4.0. Users of open-source LLVM.org compiler releases can use these features starting with clang v3.1.<p>
28
29These language additions simplify common Objective-C programming patterns, make programs more concise, and improve the safety of container creation.<p>
30
31This document describes how the features are implemented in clang, and how to use them in your own programs.<p>
32
33<h2>NSNumber Literals</h2>
34
35The framework class <code>NSNumber</code> is used to wrap scalar values inside objects: signed and unsigned integers (<code>char</code>, <code>short</code>, <code>int</code>, <code>long</code>, <code>long long</code>), floating point numbers (<code>float</code>, <code>double</code>), and boolean values (<code>BOOL</code>, C++ <code>bool</code>). Scalar values wrapped in objects are also known as <i>boxed</i> values.<p>
36
37In Objective-C, any character, numeric or boolean literal prefixed with the <code>'@'</code> character will evaluate to a pointer to an <code>NSNumber</code> object initialized with that value. C's type suffixes may be used to control the size of numeric literals.
38
39<h3>Examples</h3>
40
41The following program illustrates the rules for <code>NSNumber</code> literals:<p>
42
43<pre>
44void main(int argc, const char *argv[]) {
45 // character literals.
46 NSNumber *theLetterZ = @'Z'; // equivalent to [NSNumber numberWithChar:'Z']
47
48 // integral literals.
49 NSNumber *fortyTwo = @42; // equivalent to [NSNumber numberWithInt:42]
50 NSNumber *fortyTwoUnsigned = @42U; // equivalent to [NSNumber numberWithUnsignedInt:42U]
51 NSNumber *fortyTwoLong = @42L; // equivalent to [NSNumber numberWithLong:42L]
52 NSNumber *fortyTwoLongLong = @42LL; // equivalent to [NSNumber numberWithLongLong:42LL]
53
54 // floating point literals.
55 NSNumber *piFloat = @3.141592654F; // equivalent to [NSNumber numberWithFloat:3.141592654F]
56 NSNumber *piDouble = @3.1415926535; // equivalent to [NSNumber numberWithDouble:3.1415926535]
57
58 // BOOL literals.
59 NSNumber *yesNumber = @YES; // equivalent to [NSNumber numberWithBool:YES]
60 NSNumber *noNumber = @NO; // equivalent to [NSNumber numberWithBool:NO]
61
62#ifdef __cplusplus
63 NSNumber *trueNumber = @true; // equivalent to [NSNumber numberWithBool:(BOOL)true]
64 NSNumber *falseNumber = @false; // equivalent to [NSNumber numberWithBool:(BOOL)false]
65#endif
66}
67</pre>
68
69<h3>Discussion</h3>
70
71NSNumber literals only support literal scalar values after the '@'. Consequently, @INT_MAX works, but @INT_MIN does not, because they are defined like this:<p>
72
73<pre>
74#define INT_MAX 2147483647 /* max value for an int */
75#define INT_MIN (-2147483647-1) /* min value for an int */
76</pre>
77
78The definition of INT_MIN is not a simple literal, but a parenthesized expression. This is by design, but may be improved in subsequent compiler releases.<p>
79
80Because <code>NSNumber</code> does not currently support wrapping <code>long double</code> values, the use of a <code>long double NSNumber</code> literal (e.g. <code>@123.23L</code>) will be rejected by the compiler.<p>
81
82Previously, the <code>BOOL</code> type was simply a typedef for <code>signed char</code>, and <code>YES</code> and <code>NO</code> were macros that expand to <code>(BOOL)1</code> and <code>(BOOL)0</code> respectively. To support <code>@YES</code> and <code>@NO</code> expressions, these macros are now defined using new language keywords in <code>&LT;objc/objc.h&GT;</code>:<p>
83
84<pre>
85#if __has_feature(objc_bool)
86#define YES __objc_yes
87#define NO __objc_no
88#else
89#define YES ((BOOL)1)
90#define NO ((BOOL)0)
91#endif
92</pre>
93
94The compiler implicitly converts <code>__objc_yes</code> and <code>__objc_no</code> to <code>(BOOL)1</code> and <code>(BOOL)0</code>. The keywords are used to disambiguate <code>BOOL</code> and integer literals.<p>
95
96Objective-C++ also supports <code>@true</code> and <code>@false</code> expressions, which are equivalent to <code>@YES</code> and <code>@NO</code>.
97
98
99<h2>Container Literals</h2>
100
101Objective-C now supports a new expression syntax for creating immutable array and dictionary container objects.
102
103<h3>Examples</h3>
104
105Immutable array expression:<p>
106
107 <pre>
108NSArray *array = @[ @"Hello", NSApp, [NSNumber numberWithInt:42] ];
109</pre>
110
111This creates an <code>NSArray</code> with 3 elements. The comma-separated sub-expressions of an array literal can be any Objective-C object pointer typed expression.<p>
112
113Immutable dictionary expression:<p>
114
115<pre>
116NSDictionary *dictionary = @{
117 @"name" : NSUserName(),
118 @"date" : [NSDate date],
119 @"processInfo" : [NSProcessInfo processInfo]
120};
121</pre>
122
Patrick Beardca7f5bd2012-03-20 21:09:25 +0000123This creates an <code>NSDictionary</code> with 3 key/value pairs. Value sub-expressions of a dictionary literal must be Objective-C object pointer typed, as in array literals. Key sub-expressions must be of an Objective-C object pointer type that implements the <code>&LT;NSCopying&GT;</code> protocol.<p>
Patrick Beardaf39ba12012-03-20 20:50:45 +0000124
125<h3>Discussion</h3>
126
Patrick Beardca7f5bd2012-03-20 21:09:25 +0000127Neither keys nor values can have the value <code>nil</code> in containers. If the compiler can prove that a key or value is <code>nil</code> at compile time, then a warning will be emitted. Otherwise, a runtime error will occur.<p>
Patrick Beardaf39ba12012-03-20 20:50:45 +0000128
129Using array and dictionary literals is safer than the variadic creation forms commonly in use today. Array literal expressions expand to calls to <code>+[NSArray arrayWithObjects:count:]</code>, which validates that all objects are non-<code>nil</code>. The variadic form, <code>+[NSArray arrayWithObjects:]</code> uses <code>nil</code> as an argument list terminator, which can lead to malformed array objects. Dictionary literals are similarly created with <code>+[NSDictionary dictionaryWithObjects:forKeys:count:]</code> which validates all objects and keys, unlike <code>+[NSDictionary dictionaryWithObjectsAndKeys:]</code> which also uses a <code>nil</code> parameter as an argument list terminator.<p>
130
131<h2>Object Subscripting</h2>
132
133Objective-C object pointer values can now be used with C's subscripting operator.<p>
134
135<h3>Examples</h3>
136
137The following code demonstrates the use of object subscripting syntax with <code>NSMutableArray</code> and <code>NSMutableDictionary</code> objects:<p>
138
139<pre>
140NSMutableArray *array = ...;
141NSUInteger idx = ...;
142id newObject = ...;
143id oldObject = array[idx];
144array[idx] = newObject; // replace oldObject with newObject
145
146NSMutableDictionary *dictionary = ...;
147NSString *key = ...;
148oldObject = dictionary[key];
149dictionary[key] = newObject; // replace oldObject with newObject
150</pre>
151
152The next section explains how subscripting expressions map to accessor methods.<p>
153
154<h3>Subscripting Methods</h3>
155
156Objective-C supports two kinds of subscript expressions: <i>array-style</i> subscript expressions use integer typed subscripts; <i>dictionary-style</i> subscript expressions use Objective-C object pointer typed subscripts. Each type of subscript expression is mapped to a message send using a predefined selector. The advantage of this design is flexibility: class designers are free to introduce subscripting by declaring methods or by adopting protocols. Moreover, because the method names are selected by the type of the subscript, an object can be subscripted using both array and dictionary styles.
157
158<h4>Array-Style Subscripting</h4>
159
160When the subscript operand has an integral type, the expression is rewritten to use one of two different selectors, depending on whether the element is being read or written. When an expression reads an element using an integral index, as in the following example:<p>
161
162<pre>
163NSUInteger idx = ...;
164id value = object[idx];
165</pre>
166
167it is translated into a call to <code>objectAtIndexedSubscript:</code><p>
168
169<pre>
170id value = [object objectAtIndexedSubscript:idx];
171</pre>
172
173When an expression writes an element using an integral index:<p>
174
175<pre>
176object[idx] = newValue;
177</pre>
178
179it is translated to a call to <code>setObject:atIndexedSubscript:</code><p>
180
181<pre>
182[object setObject:newValue atIndexedSubscript:idx];
183</pre>
184
185These message sends are then type-checked and performed just like explicit message sends. The method used for objectAtIndexedSubscript: must be declared with an argument of integral type and a return value of some Objective-C object pointer type. The method used for setObject:atIndexedSubscript: must be declared with its first argument having some Objective-C pointer type and its second argument having integral type.<p>
186
187The meaning of indexes is left up to the declaring class. The compiler will coerce the index to the appropriate argument type of the method it uses for type-checking. For an instance of <code>NSArray</code>, reading an element using an index outside the range <code>[0, array.count)</code> will raise an exception. For an instance of <code>NSMutableArray</code>, assigning to an element using an index within this range will replace that element, but assigning to an element using an index outside this range will raise an exception; no syntax is provided for inserting, appending, or removing elements for mutable arrays.<p>
188
189A class need not declare both methods in order to take advantage of this language feature. For example, the class <code>NSArray</code> declares only <code>objectAtIndexedSubscript:</code>, so that assignments to elements will fail to type-check; moreover, its subclass <code>NSMutableArray</code> declares <code>setObject:atIndexedSubscript:</code>.
190
191<h4>Dictionary-Style Subscripting</h4>
192
193When the subscript operand has an Objective-C object pointer type, the expression is rewritten to use one of two different selectors, depending on whether the element is being read from or written to. When an expression reads an element using an Objective-C object pointer subscript operand, as in the following example:<p>
194
195<pre>
196id key = ...;
197id value = object[key];
198</pre>
199
200it is translated into a call to the <code>objectForKeyedSubscript:</code> method:<p>
201
202<pre>
203id value = [object objectForKeyedSubscript:key];
204</pre>
205
206When an expression writes an element using an Objective-C object pointer subscript:<p>
207
208<pre>
209object[key] = newValue;
210</pre>
211
212it is translated to a call to <code>setObject:forKeyedSubscript:</code>
213
214<pre>
215[object setObject:newValue forKeyedSubscript:key];
216</pre>
217
218The behavior of <code>setObject:forKeyedSubscript:</code> is class-specific; but in general it should replace an existing value if one is already associated with a key, otherwise it should add a new value for the key. No syntax is provided for removing elements from mutable dictionaries.<p>
219
220<h3>Discussion</h3>
221
222An Objective-C subscript expression occurs when the base operand of the C subscript operator has an Objective-C object pointer type. Since this potentially collides with pointer arithmetic on the value, these expressions are only supported under the modern Objective-C runtime, which categorically forbids such arithmetic.<p>
223
224Currently, only subscripts of integral or Objective-C object pointer type are supported. In C++, a class type can be used if it has a single conversion function to an integral or Objective-C pointer type, in which case that conversion is applied and analysis continues as appropriate. Otherwise, the expression is ill-formed.<p>
225
226An Objective-C object subscript expression is always an l-value. If the expression appears on the left-hand side of a simple assignment operator (=), the element is written as described below. If the expression appears on the left-hand side of a compound assignment operator (e.g. +=), the program is ill-formed, because the result of reading an element is always an Objective-C object pointer and no binary operators are legal on such pointers. If the expression appears in any other position, the element is read as described below. It is an error to take the address of a subscript expression, or (in C++) to bind a reference to it.<p>
227
228Programs can use object subscripting with Objective-C object pointers of type <code>id</code>. Normal dynamic message send rules apply; the compiler must see <i>some</i> declaration of the subscripting methods, and will pick the declaration seen first.<p>
229
230<h2>Grammar Additions</h2>
231
232To support the new syntax described above, the Objective-C <code>@</code>-expression grammar has the following new productions:<p>
233
234<pre>
235objc-at-expression : '@' (string-literal | encode-literal | selector-literal | protocol-literal | object-literal)
236 ;
237
238object-literal : ('+' | '-')? numeric-constant
239 | character-constant
240 | boolean-constant
241 | array-literal
242 | dictionary-literal
243 ;
244
245boolean-constant : '__objc_yes' | '__objc_no' | 'true' | 'false' /* boolean keywords. */
246 ;
247
248array-literal : '[' assignment-expression-list ']'
249 ;
250
251assignment-expression-list : assignment-expression (',' assignment-expression-list)?
252 | /* empty */
253 ;
254
255dictionary-literal : '{' key-value-list '}'
256 ;
257
258key-value-list : key-value-pair (',' key-value-list)?
259 | /* empty */
260 ;
261
262key-value-pair : assignment-expression ':' assignment-expression
263 ;
264</pre>
265
266Note: <code>@true</code> and <code>@false</code> are only supported in Objective-C++.<p>
267
268<h2>Availability Checks</h2>
269
270Programs test for the new features by using clang's __has_feature checks. Here are examples of their use:<p>
271
272<pre>
273#if __has_feature(objc_array_literals)
274 // new way.
275 NSArray *elements = @[ @"H", @"He", @"O", @"C" ];
276#else
277 // old way (equivalent).
278 id objects[] = { @"H", @"He", @"O", @"C" };
279 NSArray *elements = [NSArray arrayWithObjects:objects count:4];
280#endif
281
282#if __has_feature(objc_dictionary_literals)
283 // new way.
284 NSDictionary *masses = @{ @"H" : @1.0078, @"He" : @4.0026, @"O" : @15.9990, @"C" : @12.0096 };
285#else
286 // old way (equivalent).
287 id keys[] = { @"H", @"He", @"O", @"C" };
Patrick Bearda62c3802012-03-20 22:24:08 +0000288 id values[] = { [NSNumber numberWithDouble:1.0078], [NSNumber numberWithDouble:4.0026],
289 [NSNumber numberWithDouble:15.9990], [NSNumber numberWithDouble:12.0096] };
Patrick Beardaf39ba12012-03-20 20:50:45 +0000290 NSDictionary *masses = [NSDictionary dictionaryWithObjects:objects forKeys:keys count:4];
291#endif
292
293#if __has_feature(objc_subscripting)
294 NSUInteger i, count = elements.count;
295 for (i = 0; i < count; ++i) {
296 NSString *element = elements[i];
297 NSNumber *mass = masses[element];
298 NSLog(@"the mass of %@ is %@", element, mass);
299 }
300#else
301 NSUInteger i, count = [elements count];
302 for (i = 0; i < count; ++i) {
303 NSString *element = [elements objectAtIndex:i];
304 NSNumber *mass = [masses objectForKey:element];
305 NSLog(@"the mass of %@ is %@", element, mass);
306 }
307#endif
308</pre>
309
310Code can use also <code>__has_feature(objc_bool)</code> to check for the availability of numeric literals support. This checks for the new <code>__objc_yes / __objc_no</code> keywords, which enable the use of <code>@YES / @NO</code> literals.<p>
311
312</div>
313</body>
314</html>