-
Notifications
You must be signed in to change notification settings - Fork 154
/
Box.swift
1697 lines (1315 loc) · 55.3 KB
/
Box.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// 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:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE 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.
import Foundation
// "It's all boxes all the way down."
//
// Mustache templates don't eat raw values: they eat boxed values.
//
// To box something, you use the `Box()` function. It comes in several variants
// so that nearly anything can be boxed and feed templates:
//
// let value = ...
// template.render(Box(value))
//
// This file is organized in five sections with many examples. You can use the
// Playground included in `Mustache.xcworkspace` to run those examples.
//
//
// - MustacheBoxable and the Boxing of Value Types
//
// The `MustacheBoxable` protocol lets any type describe how it interacts with
// the Mustache rendering engine.
//
// It is adopted by the standard types Bool, Int, UInt, Double, String, and
// NSObject.
//
//
// - Boxing of Collections
//
// Learn how Array and Set are rendered.
//
//
// - Boxing of Dictionaries
//
// Learn how Dictionary and NSDictionary are rendered.
//
//
// - Boxing of Core Mustache functions
//
// The "core Mustache functions" are raw filters, Mustache lambdas, etc. Those
// can be boxed as well so that you can feed templates with them.
//
//
// - Boxing of multi-facetted values
//
// Describes the most advanced `Box()` function.
// =============================================================================
// MARK: - MustacheBoxable and the Boxing of Value Types
/**
The MustacheBoxable protocol gives any type the ability to feed Mustache
templates.
It is adopted by the standard types Bool, Int, UInt, Double, String, and
NSObject.
Your own types can conform to it as well, so that they can feed templates:
extension Profile: MustacheBoxable { ... }
let profile = ...
let template = try! Template(named: "Profile")
let rendering = try! template.render(Box(profile))
*/
public protocol MustacheBoxable {
/**
You should not directly call the `mustacheBox` property. Always use the
`Box()` function instead:
value.mustacheBox // Valid, but discouraged
Box(value) // Preferred
Return a `MustacheBox` that describes how your type interacts with the
rendering engine.
You can for example box another value that is already boxable, such as
dictionaries:
struct Person {
let firstName: String
let lastName: String
}
extension Person : MustacheBoxable {
// Expose the `firstName`, `lastName` and `fullName` keys to
// Mustache templates:
var mustacheBox: MustacheBox {
return Box([
"firstName": firstName,
"lastName": lastName,
"fullName": "\(self.firstName) \(self.lastName)",
])
}
}
let person = Person(firstName: "Tom", lastName: "Selleck")
// Renders "Tom Selleck"
let template = try! Template(string: "{{person.fullName}}")
try! template.render(Box(["person": Box(person)]))
However, there are multiple ways to build a box, several `Box()` functions.
See their documentations.
*/
var mustacheBox: MustacheBox { get }
}
// IMPLEMENTATION NOTE
//
// This protocol conformance is not only a matter of consistency. It is also
// a convenience for the library implementation: it makes arrays
// [MustacheBox] boxable via Box<C: CollectionType where C.Generator.Element: MustacheBoxable>(collection: C?)
// and dictionaries [String:MustacheBox] boxable via Box<T: MustacheBoxable>(dictionary: [String: T]?)
extension MustacheBox {
/**
`MustacheBox` adopts the `MustacheBoxable` protocol so that it can feed
Mustache templates. Its mustacheBox property returns itself.
*/
public override var mustacheBox: MustacheBox {
return self
}
}
/**
GRMustache provides built-in support for rendering `Bool`.
*/
extension Bool : MustacheBoxable {
/**
`Bool` adopts the `MustacheBoxable` protocol so that it can feed Mustache
templates.
You should not directly call the `mustacheBox` property. Always use the
`Box()` function instead:
true.mustacheBox // Valid, but discouraged
Box(true) // Preferred
### Rendering
- `{{bool}}` renders as `0` or `1`.
- `{{#bool}}...{{/bool}}` renders if and only if `bool` is true.
- `{{^bool}}...{{/bool}}` renders if and only if `bool` is false.
*/
public var mustacheBox: MustacheBox {
return MustacheBox(
value: self,
boolValue: self,
render: { (info: RenderingInfo) in
switch info.tag.type {
case .Variable:
// {{ bool }}
return Rendering("\(self ? 1 : 0)") // Behave like [NSNumber numberWithBool:]
case .Section:
if info.enumerationItem {
// {{# bools }}...{{/ bools }}
return try info.tag.render(info.context.extendedContext(Box(self)))
} else {
// {{# bool }}...{{/ bool }}
//
// Bools do not enter the context stack when used in a
// boolean section.
//
// This behavior must not change:
// https://github.com/groue/GRMustache/issues/83
return try info.tag.render(info.context)
}
}
})
}
}
/**
GRMustache provides built-in support for rendering `Int`.
*/
extension Int : MustacheBoxable {
/**
`Int` adopts the `MustacheBoxable` protocol so that it can feed Mustache
templates.
You should not directly call the `mustacheBox` property. Always use the
`Box()` function instead:
1.mustacheBox // Valid, but discouraged
Box(1) // Preferred
### Rendering
- `{{int}}` is rendered with built-in Swift String Interpolation.
Custom formatting can be explicitly required with NSNumberFormatter, as in
`{{format(a)}}` (see `NSFormatter`).
- `{{#int}}...{{/int}}` renders if and only if `int` is not 0 (zero).
- `{{^int}}...{{/int}}` renders if and only if `int` is 0 (zero).
*/
public var mustacheBox: MustacheBox {
return MustacheBox(
value: self,
boolValue: (self != 0),
render: { (info: RenderingInfo) in
switch info.tag.type {
case .Variable:
// {{ int }}
return Rendering("\(self)")
case .Section:
if info.enumerationItem {
// {{# ints }}...{{/ ints }}
return try info.tag.render(info.context.extendedContext(Box(self)))
} else {
// {{# int }}...{{/ int }}
//
// Ints do not enter the context stack when used in a
// boolean section.
//
// This behavior must not change:
// https://github.com/groue/GRMustache/issues/83
return try info.tag.render(info.context)
}
}
})
}
}
/**
GRMustache provides built-in support for rendering `UInt`.
*/
extension UInt : MustacheBoxable {
/**
`UInt` adopts the `MustacheBoxable` protocol so that it can feed Mustache
templates.
You should not directly call the `mustacheBox` property. Always use the
`Box()` function instead:
1.mustacheBox // Valid, but discouraged
Box(1) // Preferred
### Rendering
- `{{uint}}` is rendered with built-in Swift String Interpolation.
Custom formatting can be explicitly required with NSNumberFormatter, as in
`{{format(a)}}` (see `NSFormatter`).
- `{{#uint}}...{{/uint}}` renders if and only if `uint` is not 0 (zero).
- `{{^uint}}...{{/uint}}` renders if and only if `uint` is 0 (zero).
*/
public var mustacheBox: MustacheBox {
return MustacheBox(
value: self,
boolValue: (self != 0),
render: { (info: RenderingInfo) in
switch info.tag.type {
case .Variable:
// {{ uint }}
return Rendering("\(self)")
case .Section:
if info.enumerationItem {
// {{# uints }}...{{/ uints }}
return try info.tag.render(info.context.extendedContext(Box(self)))
} else {
// {{# uint }}...{{/ uint }}
//
// Uints do not enter the context stack when used in a
// boolean section.
//
// This behavior must not change:
// https://github.com/groue/GRMustache/issues/83
return try info.tag.render(info.context)
}
}
})
}
}
/**
GRMustache provides built-in support for rendering `Double`.
*/
extension Double : MustacheBoxable {
/**
`Double` adopts the `MustacheBoxable` protocol so that it can feed Mustache
templates.
You should not directly call the `mustacheBox` property. Always use the
`Box()` function instead:
3.14.mustacheBox // Valid, but discouraged
Box(3.14) // Preferred
### Rendering
- `{{double}}` is rendered with built-in Swift String Interpolation.
Custom formatting can be explicitly required with NSNumberFormatter, as in
`{{format(a)}}` (see `NSFormatter`).
- `{{#double}}...{{/double}}` renders if and only if `double` is not 0 (zero).
- `{{^double}}...{{/double}}` renders if and only if `double` is 0 (zero).
*/
public var mustacheBox: MustacheBox {
return MustacheBox(
value: self,
boolValue: (self != 0.0),
render: { (info: RenderingInfo) in
switch info.tag.type {
case .Variable:
// {{ double }}
return Rendering("\(self)")
case .Section:
if info.enumerationItem {
// {{# doubles }}...{{/ doubles }}
return try info.tag.render(info.context.extendedContext(Box(self)))
} else {
// {{# double }}...{{/ double }}
//
// Doubles do not enter the context stack when used in a
// boolean section.
//
// This behavior must not change:
// https://github.com/groue/GRMustache/issues/83
return try info.tag.render(info.context)
}
}
})
}
}
/**
GRMustache provides built-in support for rendering `String`.
*/
extension String : MustacheBoxable {
/**
`String` adopts the `MustacheBoxable` protocol so that it can feed Mustache
templates.
You should not directly call the `mustacheBox` property. Always use the
`Box()` function instead:
"foo".mustacheBox // Valid, but discouraged
Box("foo") // Preferred
### Rendering
- `{{string}}` renders the string, HTML-escaped.
- `{{{string}}}` renders the string, *not* HTML-escaped.
- `{{#string}}...{{/string}}` renders if and only if `string` is not empty.
- `{{^string}}...{{/string}}` renders if and only if `string` is empty.
HTML-escaping of `{{string}}` tags is disabled for Text templates: see
`Configuration.contentType` for a full discussion of the content type of
templates.
### Keys exposed to templates
A string can be queried for the following keys:
- `length`: the number of characters in the string.
*/
public var mustacheBox: MustacheBox {
return MustacheBox(
value: self,
boolValue: (self.characters.count > 0),
keyedSubscript: { (key: String) in
switch key {
case "length":
return Box(self.characters.count)
default:
return Box()
}
})
}
}
/**
GRMustache provides built-in support for rendering `NSObject`.
*/
extension NSObject : MustacheBoxable {
/**
`NSObject` adopts the `MustacheBoxable` protocol so that it can feed
Mustache templates.
You should not directly call the `mustacheBox` property. Always use the
`Box()` function instead:
object.mustacheBox // Valid, but discouraged
Box(object) // Preferred
NSObject's default implementation handles two general cases:
- Enumerable objects that conform to the `NSFastEnumeration` protocol, such
as `NSArray` and `NSOrderedSet`.
- All other objects
GRMustache ships with a few specific classes that escape the general cases
and provide their own rendering behavior: `NSDictionary`, `NSFormatter`,
`NSNull`, `NSNumber`, `NSString`, and `NSSet` (see the documentation for
those classes).
Your own subclasses of NSObject can also override the `mustacheBox` method
and provide their own custom behavior.
## Arrays
An object is treated as an array if it conforms to `NSFastEnumeration`. This
is the case of `NSArray` and `NSOrderedSet`, for example. `NSDictionary` and
`NSSet` have their own custom Mustache rendering: see their documentation
for more information.
### Rendering
- `{{array}}` renders the concatenation of the renderings of the array items.
- `{{#array}}...{{/array}}` renders as many times as there are items in
`array`, pushing each item on its turn on the top of the context stack.
- `{{^array}}...{{/array}}` renders if and only if `array` is empty.
### Keys exposed to templates
An array can be queried for the following keys:
- `count`: number of elements in the array
- `first`: the first object in the array
- `last`: the last object in the array
Because 0 (zero) is falsey, `{{#array.count}}...{{/array.count}}` renders
once, if and only if `array` is not empty.
## Other objects
Other objects fall in the general case.
Their keys are extracted with the `valueForKey:` method, as long as the key
is a property name, a custom property getter, or the name of a
`NSManagedObject` attribute.
### Rendering
- `{{object}}` renders the result of the `description` method, HTML-escaped.
- `{{{object}}}` renders the result of the `description` method, *not*
HTML-escaped.
- `{{#object}}...{{/object}}` renders once, pushing `object` on the top of
the context stack.
- `{{^object}}...{{/object}}` does not render.
*/
public var mustacheBox: MustacheBox {
if let enumerable = self as? NSFastEnumeration {
// Enumerable
// Turn enumerable into a Swift array of MustacheBoxes that we know how to box
let array = GeneratorSequence(NSFastGenerator(enumerable)).map(BoxAnyObject)
return array.mustacheBoxWithArrayValue(self, box: { $0 })
} else {
// Generic NSObject
#if OBJC
return MustacheBox(
value: self,
keyedSubscript: { (key: String) in
if GRMustacheKeyAccess.isSafeMustacheKey(key, forObject: self) {
// Use valueForKey: for safe keys
return BoxAnyObject(self.valueForKey(key))
} else {
// Missing key
return Box()
}
})
#else
return MustacheBox(value: self)
#endif
}
}
}
/**
GRMustache provides built-in support for rendering `NSNull`.
*/
extension NSNull {
/**
`NSNull` adopts the `MustacheBoxable` protocol so that it can feed Mustache
templates.
You should not directly call the `mustacheBox` property. Always use the
`Box()` function instead:
NSNull().mustacheBox // Valid, but discouraged
Box(NSNull()) // Preferred
### Rendering
- `{{null}}` does not render.
- `{{#null}}...{{/null}}` does not render (NSNull is falsey).
- `{{^null}}...{{/null}}` does render (NSNull is falsey).
*/
public override var mustacheBox: MustacheBox {
return MustacheBox(
value: self,
boolValue: false,
render: { (info: RenderingInfo) in return Rendering("") })
}
}
/**
GRMustache provides built-in support for rendering `NSNumber`.
*/
extension NSNumber {
/**
`NSNumber` adopts the `MustacheBoxable` protocol so that it can feed
Mustache templates.
You should not directly call the `mustacheBox` property. Always use the
`Box()` function instead:
NSNumber(integer: 1).mustacheBox // Valid, but discouraged
Box(NSNumber(integer: 1)) // Preferred
### Rendering
NSNumber renders exactly like Swift numbers: depending on its internal
objCType, an NSNumber is rendered as a Swift Bool, Int, UInt, or Double.
- `{{number}}` is rendered with built-in Swift String Interpolation.
Custom formatting can be explicitly required with NSNumberFormatter, as in
`{{format(a)}}` (see `NSFormatter`).
- `{{#number}}...{{/number}}` renders if and only if `number` is not 0 (zero).
- `{{^number}}...{{/number}}` renders if and only if `number` is 0 (zero).
*/
public override var mustacheBox: MustacheBox {
// IMPLEMENTATION NOTE
//
// Don't event think about wrapping unsigned values in an Int, even if
// Int is large enough to store these values without information loss.
// This would make template rendering depend on the size of Int, and
// yield very weird platform-related issues. So keep it simple, stupid.
let objCType = String.fromCString(self.objCType)!
switch objCType {
case "c":
return Box(Int(charValue))
case "C":
return Box(UInt(unsignedCharValue))
case "s":
return Box(Int(shortValue))
case "S":
return Box(UInt(unsignedShortValue))
case "i":
return Box(Int(intValue))
case "I":
return Box(UInt(unsignedIntValue))
case "l":
return Box(Int(longValue))
case "L":
return Box(UInt(unsignedLongValue))
case "q":
return Box(Int(longLongValue)) // May fail on 32-bits architectures, right?
case "Q":
return Box(UInt(unsignedLongLongValue)) // May fail on 32-bits architectures, right?
case "f":
return Box(Double(floatValue))
case "d":
return Box(doubleValue)
case "B":
return Box(boolValue)
default:
NSLog("GRMustache support for NSNumber of type \(objCType) is not implemented: value is discarded.")
return Box()
}
}
}
/**
GRMustache provides built-in support for rendering `NSString`.
*/
extension NSString {
/**
`NSString` adopts the `MustacheBoxable` protocol so that it can feed
Mustache templates.
You should not directly call the `mustacheBox` property. Always use the
`Box()` function instead:
"foo".mustacheBox // Valid, but discouraged
Box("foo") // Preferred
### Rendering
- `{{string}}` renders the string, HTML-escaped.
- `{{{string}}}` renders the string, *not* HTML-escaped.
- `{{#string}}...{{/string}}` renders if and only if `string` is not empty.
- `{{^string}}...{{/string}}` renders if and only if `string` is empty.
HTML-escaping of `{{string}}` tags is disabled for Text templates: see
`Configuration.contentType` for a full discussion of the content type of
templates.
### Keys exposed to templates
A string can be queried for the following keys:
- `length`: the number of characters in the string (using Swift method).
*/
public override var mustacheBox: MustacheBox {
return Box(self as String)
}
}
/**
Values that conform to the `MustacheBoxable` protocol can feed Mustache
templates.
- parameter boxable: An optional value that conform to the `MustacheBoxable`
protocol.
- returns: A MustacheBox that wraps *boxable*.
*/
public func Box(boxable: MustacheBoxable?) -> MustacheBox {
return boxable?.mustacheBox ?? Box()
}
// IMPLEMENTATION NOTE
//
// Why is there a Box(NSObject?) function, when Box(MustacheBoxable?) should be
// enough, given NSObject adopts MustacheBoxable?
//
// Well, this is another Swift oddity.
//
// Without this explicit NSObject support, many compound values like the ones
// below could not be boxed:
//
// - ["cats": ["Kitty", "Pussy", "Melba"]]
// - [[0,1],[2,3]]
//
// It looks like Box(object: NSObject?) triggers the silent conversion of those
// values to NSArray and NSDictionary.
//
// It's an extra commodity we want to keep, in order to prevent the user to
// rewrite them as:
//
// - ["cats": Box([Box("Kitty"), Box("Pussy"), Box("Melba")])]
// - [Box([0,1]), Box([2,3])]
/**
See the documentation of `NSObject.mustacheBox`.
- parameter object: An NSObject.
- returns: A MustacheBox that wraps *object*.
*/
public func Box(object: NSObject?) -> MustacheBox {
return object?.mustacheBox ?? Box()
}
// IMPLEMENTATION NOTE
//
// Why is there a BoxAnyObject(AnyObject?) function, but no Box(AnyObject?)
//
// GRMustache aims at having a single boxing function: Box(), with many
// overloaded variants. This lets the user box anything, standard Swift types
// (Bool, String, etc.), custom types, as well as opaque types (such as
// StandardLibrary.javascriptEscape).
//
// For example:
//
// public func Box(boxable: MustacheBoxable?) -> MustacheBox
// public func Box(filter: FilterFunction) -> MustacheBox
//
// Sometimes values come out of Foundation objects:
//
// class NSDictionary {
// subscript (key: NSCopying) -> AnyObject? { get }
// }
//
// So we need a Box(AnyObject?) function, right?
//
// Unfortunately, this will not work:
//
// protocol MustacheBoxable {}
// class Thing: MustacheBoxable {}
//
// func Box(x: MustacheBoxable?) -> String { return "MustacheBoxable" }
// func Box(x: AnyObject?) -> String { return "AnyObject" }
//
// // error: ambiguous use of 'Box'
// Box(Thing())
//
// Maybe if we turn the func Box(x: MustacheBoxable?) into a generic one? Well,
// it does not make the job either:
//
// protocol MustacheBoxable {}
// class Thing: MustacheBoxable {}
//
// func Box<T: MustacheBoxable>(x: T?) -> String { return "MustacheBoxable" }
// func Box(x: AnyObject?) -> String { return "AnyObject" }
//
// // Wrong: uses the AnyObject variant
// Box(Thing())
//
// // Error: cannot find an overload for 'Box' that accepts an argument list of type '(MustacheBoxable)'
// Box(Thing() as MustacheBoxable)
//
// // Error: Crash the compiler
// Box(Thing() as MustacheBoxable?)
//
// And if we turn the func Box(x: AnyObject) into a generic one? Well, it gets
// better:
//
// protocol MustacheBoxable {}
// class Thing: MustacheBoxable {}
//
// func Box(x: MustacheBoxable?) -> String { return "MustacheBoxable" }
// func Box<T:AnyObject>(object: T?) -> String { return "AnyObject" }
//
// // OK: uses the MustacheBox variant
// Box(Thing())
//
// // OK: uses the MustacheBox variant
// Box(Thing() as MustacheBoxable)
//
// // OK: uses the MustacheBox variant
// Box(Thing() as MustacheBoxable?)
//
// // OK: uses the AnyObject variant
// Box(Thing() as AnyObject)
//
// // OK: uses the AnyObject variant
// Box(Thing() as AnyObject?)
//
// This looks OK, doesn't it? Well, it's not satisfying yet.
//
// According to http://airspeedvelocity.net/2015/03/26/protocols-and-generics-2/
// there are reasons for preferring func Box<T: MustacheBoxable>(x: T?) over
// func Box(x: MustacheBoxable?). The example above have shown that the boxing
// of AnyObject with an overloaded version of Box() would make this choice for
// us.
//
// It's better not to make any choice right now, until we have a better
// knowledge of Swift performances and optimization, and of the way Swift
// resolves overloaded functions.
//
// So let's avoid having any Box(AnyObject?) variant in the public API, and
// let's expose the BoxAnyObject(object: AnyObject?) instead.
// IMPLEMENTATION NOTE 2
//
// BoxAnyObject has been made private. Now users get a compiler error when they
// try to box AnyObject.
//
// Reasons for this removal from the public API:
//
// - Users will try Box() first, which will fail. Since they may not know
// anything BoxAnyObject, BoxAnyObject is of little value anyway.
// - BoxAnyObject is error-prone, since it accepts anything and fails at
// runtime.
//
// It still exists because we need it to box Foundation collections like
// NSArray, NSSet, NSDictionary.
/**
`AnyObject` can feed Mustache templates.
Yet, due to constraints in the Swift language, there is no `Box(AnyObject)`
function. Instead, you use `BoxAnyObject`:
let set = NSSet(object: "Mario")
let object: AnyObject = set.anyObject()
let box = BoxAnyObject(object)
box.value as String // "Mario"
The object is tested at runtime whether it adopts the `MustacheBoxable`
protocol. In this case, this function behaves just like `Box(MustacheBoxable)`.
Otherwise, GRMustache logs a warning, and returns the empty box.
- parameter object: An object.
- returns: A MustacheBox that wraps *object*.
*/
private func BoxAnyObject(object: AnyObject?) -> MustacheBox {
if let boxable = object as? MustacheBoxable {
return boxable.mustacheBox
} else if let object: AnyObject = object {
// IMPLEMENTATION NOTE
//
// In the example below, the Thing class can not be turned into any
// relevant MustacheBox.
//
// Yet we can not prevent the user from trying to box it, because the
// Thing class adopts the AnyObject protocol, just as all Swift classes.
//
// class Thing { }
//
// // Compilation error (OK): cannot find an overload for 'Box' that accepts an argument list of type '(Thing)'
// Box(Thing())
//
// // Runtime warning (Not OK but unavoidable): value `Thing` is not NSObject and does not conform to MustacheBoxable: it is discarded.
// BoxAnyObject(Thing())
//
// // Foundation collections can also contain unsupported classes:
// let array = NSArray(object: Thing())
//
// // Runtime warning (Not OK but unavoidable): value `Thing` is not NSObject and does not conform to MustacheBoxable: it is discarded.
// Box(array)
//
// // Compilation error (OK): cannot find an overload for 'Box' that accepts an argument list of type '(AnyObject)'
// Box(array[0])
//
// // Runtime warning (Not OK but unavoidable): value `Thing` is not NSObject and does not conform to MustacheBoxable: it is discarded.
// BoxAnyObject(array[0])
NSLog("Mustache.BoxAnyObject(): value `\(object)` is does not conform to MustacheBoxable: it is discarded.")
return Box()
} else {
return Box()
}
}
// =============================================================================
// MARK: - Boxing of Collections
// IMPLEMENTATION NOTE
//
// We don't provide any boxing function for `SequenceType`, because this type
// makes no requirement on conforming types regarding whether they will be
// destructively "consumed" by iteration (as stated by documentation).
//
// Now we need to consume a sequence several times:
//
// - for converting it to an array for the arrayValue property.
// - for consuming the first element to know if the sequence is empty or not.
// - for rendering it.
//
// So we don't support boxing of sequences.
// Support for all collections
extension CollectionType {
/**
Concatenates the rendering of the collection items.
There are two tricks when rendering collections:
1. Items can render as Text or HTML, and our collection should render with
the same type. It is an error to mix content types.
2. We have to tell items that they are rendered as an enumeration item.
This allows collections to avoid enumerating their items when they are
part of another collections:
{{# arrays }} // Each array renders as an enumeration item, and has itself enter the context stack.
{{#.}} // Each array renders "normally", and enumerates its items
...
{{/.}}
{{/ arrays }}
- parameter info: A RenderingInfo
- parameter box: A closure that turns collection items into a MustacheBox.
It makes us able to provide a single implementation
whatever the type of the collection items.
- returns: A Rendering
*/
private func renderItems(info: RenderingInfo, @noescape box: (Generator.Element) -> MustacheBox) throws -> Rendering {
// Prepare the rendering. We don't known the contentType yet: it depends on items
var buffer = ""
var contentType: ContentType? = nil
// Tell items they are rendered as an enumeration item.
//
// Some values don't render the same whenever they render as an
// enumeration item, or alone: {{# values }}...{{/ values }} vs.
// {{# value }}...{{/ value }}.
//
// This is the case of Int, UInt, Double, Bool: they enter the context
// stack when used in an iteration, and do not enter the context stack
// when used as a boolean.
//
// This is also the case of collections: they enter the context stack
// when used as an item of a collection, and enumerate their items when
// used as a collection.
var info = info
info.enumerationItem = true
for item in self {
let boxRendering = try box(item).render(info: info)
if contentType == nil
{
// First item: now we know our contentType
contentType = boxRendering.contentType
buffer += boxRendering.string
}
else if contentType == boxRendering.contentType
{
// Consistent content type: keep on buffering.
buffer += boxRendering.string
}
else
{
// Inconsistent content type: this is an error. How are we
// supposed to mix Text and HTML?
throw MustacheError(kind: .RenderError, message: "Content type mismatch")
}
}