Skip to content

Commit

Permalink
Introduce let / var macros and some further cleanup (#1012)
Browse files Browse the repository at this point in the history
* Introduce let / var and some further cleanup

* Address first comments

* Update changelog

* Move the const before auto
  • Loading branch information
maicki committed Jul 10, 2018
1 parent c8b5a1b commit 55abeed
Show file tree
Hide file tree
Showing 33 changed files with 149 additions and 131 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
- Add an experimental deallocation queue implementation that's more efficient. [Adlai Holler](https://github.com/Adlai-Holler)
- Standardize property declaration style. [Adlai Holler](https://github.com/Adlai-Holler)
- [ASTableView] Fix an issue that causes table view to use one of a cell's invalid layouts instead of generating a new one. [Huy Nguyen](https://github.com/nguyenhuy) [#942](https://github.com/TextureGroup/Texture/pull/942)
- Introduce let / var macros and some further cleanup. [Michael Schneider](https://github.com/maicki) [#1012](https://github.com/TextureGroup/Texture/pull/1012)

## 2.6
- [Xcode 9] Updated to require Xcode 9 (to fix warnings) [Garrett Moon](https://github.com/garrettmoon)
Expand Down
8 changes: 4 additions & 4 deletions Source/ASCollectionView.mm
Original file line number Diff line number Diff line change
Expand Up @@ -1545,7 +1545,7 @@ - (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath

// If the data source implements canMoveItem, let them decide.
if (_asyncDataSourceFlags.collectionNodeCanMoveItem) {
if (auto cellNode = [self nodeForItemAtIndexPath:indexPath]) {
if (let cellNode = [self nodeForItemAtIndexPath:indexPath]) {
GET_COLLECTIONNODE_OR_RETURN(collectionNode, NO);
return [_asyncDataSource collectionNode:collectionNode canMoveItemWithNode:cellNode];
}
Expand All @@ -1561,7 +1561,7 @@ - (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(N

// Inform the data source first, in case they call nodeForItemAtIndexPath:.
// We want to make sure we return them the node for the item they have in mind.
if (auto collectionNode = self.collectionNode) {
if (let collectionNode = self.collectionNode) {
[_asyncDataSource collectionNode:collectionNode moveItemAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
}

Expand Down Expand Up @@ -1996,7 +1996,7 @@ - (ASCellNodeBlock)dataController:(ASDataController *)dataController supplementa
- (NSArray<NSString *> *)dataController:(ASDataController *)dataController supplementaryNodeKindsInSections:(NSIndexSet *)sections
{
if (_asyncDataSourceFlags.collectionNodeSupplementaryElementKindsInSection) {
auto kinds = [[NSMutableSet<NSString *> alloc] init];
let kinds = [[NSMutableSet<NSString *> alloc] init];
GET_COLLECTIONNODE_OR_RETURN(collectionNode, @[]);
[sections enumerateIndexesUsingBlock:^(NSUInteger section, BOOL * _Nonnull stop) {
NSArray<NSString *> *kindsForSection = [_asyncDataSource collectionNode:collectionNode supplementaryElementKindsInSection:section];
Expand Down Expand Up @@ -2214,7 +2214,7 @@ - (void)nodesDidRelayout:(NSArray<ASCellNode *> *)nodes
return;
}

auto uikitIndexPaths = ASArrayByFlatMapping(nodes, ASCellNode *node, [self indexPathForNode:node]);
let uikitIndexPaths = ASArrayByFlatMapping(nodes, ASCellNode *node, [self indexPathForNode:node]);

[_layoutFacilitator collectionViewWillEditCellsAtIndexPaths:uikitIndexPaths batched:NO];

Expand Down
14 changes: 7 additions & 7 deletions Source/ASDisplayNode+Layout.mm
Original file line number Diff line number Diff line change
Expand Up @@ -646,8 +646,8 @@ - (void)transitionLayoutWithSizeRange:(ASSizeRange)constrainedSize
ASDN::MutexLocker l(__instanceLock__);

// Update calculated layout
auto previousLayout = _calculatedDisplayNodeLayout;
auto pendingLayout = std::make_shared<ASDisplayNodeLayout>(newLayout,
let previousLayout = _calculatedDisplayNodeLayout;
let pendingLayout = std::make_shared<ASDisplayNodeLayout>(newLayout,
constrainedSize,
constrainedSize.max,
newLayoutVersion);
Expand Down Expand Up @@ -767,10 +767,10 @@ - (void)animateLayoutTransition:(id<ASContextTransitioning>)context

NSArray<ASDisplayNode *> *removedSubnodes = [context removedSubnodes];
NSMutableArray<ASDisplayNode *> *insertedSubnodes = [[context insertedSubnodes] mutableCopy];
auto movedSubnodes = [[NSMutableArray<ASDisplayNode *> alloc] init];
let movedSubnodes = [[NSMutableArray<ASDisplayNode *> alloc] init];

auto insertedSubnodeContexts = [[NSMutableArray<_ASAnimatedTransitionContext *> alloc] init];
auto removedSubnodeContexts = [[NSMutableArray<_ASAnimatedTransitionContext *> alloc] init];
let insertedSubnodeContexts = [[NSMutableArray<_ASAnimatedTransitionContext *> alloc] init];
let removedSubnodeContexts = [[NSMutableArray<_ASAnimatedTransitionContext *> alloc] init];

for (ASDisplayNode *subnode in [context subnodesForKey:ASTransitionContextToLayoutKey]) {
if ([insertedSubnodes containsObject:subnode] == NO) {
Expand Down Expand Up @@ -905,9 +905,9 @@ - (void)_assertSubnodeState
NSArray *subnodes = [self subnodes];
NSArray *sublayouts = _calculatedDisplayNodeLayout->layout.sublayouts;

auto currentSubnodes = [[NSHashTable alloc] initWithOptions:NSHashTableObjectPointerPersonality
let currentSubnodes = [[NSHashTable alloc] initWithOptions:NSHashTableObjectPointerPersonality
capacity:subnodes.count];
auto layoutSubnodes = [[NSHashTable alloc] initWithOptions:NSHashTableObjectPointerPersonality
let layoutSubnodes = [[NSHashTable alloc] initWithOptions:NSHashTableObjectPointerPersonality
capacity:sublayouts.count];;
for (ASDisplayNode *subnode in subnodes) {
[currentSubnodes addObject:subnode];
Expand Down
4 changes: 2 additions & 2 deletions Source/ASDisplayNode.mm
Original file line number Diff line number Diff line change
Expand Up @@ -3674,7 +3674,7 @@ - (NSString *)description
- (NSString *)debugDescription
{
ASPushMainThreadAssertionsDisabled();
auto result = ASObjectDescriptionMake(self, [self propertiesForDebugDescription]);
let result = ASObjectDescriptionMake(self, [self propertiesForDebugDescription]);
ASPopMainThreadAssertionsDisabled();
return result;
}
Expand Down Expand Up @@ -3746,7 +3746,7 @@ - (NSString *)detailedLayoutDescription
{
ASPushMainThreadAssertionsDisabled();
ASDN::MutexLocker l(__instanceLock__);
auto props = [NSMutableArray<NSDictionary *> array];
let props = [[NSMutableArray<NSDictionary *> alloc] init];

[props addObject:@{ @"layoutVersion": @(_layoutVersion.load()) }];
[props addObject:@{ @"bounds": [NSValue valueWithCGRect:self.bounds] }];
Expand Down
2 changes: 1 addition & 1 deletion Source/ASImageNode.mm
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ - (UIImage *)placeholderImage

- (CGSize)calculateSizeThatFits:(CGSize)constrainedSize
{
auto image = ASLockedSelf(_image);
let image = ASLockedSelf(_image);

if (image == nil) {
return [super calculateSizeThatFits:constrainedSize];
Expand Down
2 changes: 1 addition & 1 deletion Source/ASMainThreadDeallocation.mm
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ @implementation NSObject (ASNeedsMainThreadDeallocation)

+ (BOOL)needsMainThreadDeallocation
{
auto name = class_getName(self);
let name = class_getName(self);
if (0 == strncmp(name, "AV", 2) || 0 == strncmp(name, "UI", 2) || 0 == strncmp(name, "CA", 2)) {
return YES;
}
Expand Down
14 changes: 7 additions & 7 deletions Source/ASNetworkImageNode.mm
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ - (void)displayWillStartAsynchronously:(BOOL)asynchronously
// Call out to the delegate.
if (_delegateFlags.delegateDidLoadImageWithInfo) {
ASUnlockScope(self);
auto info = [[ASNetworkImageLoadInfo alloc] initWithURL:url sourceType:ASNetworkImageSourceSynchronousCache downloadIdentifier:nil userInfo:nil];
let info = [[ASNetworkImageLoadInfo alloc] initWithURL:url sourceType:ASNetworkImageSourceSynchronousCache downloadIdentifier:nil userInfo:nil];
[_delegate imageNode:self didLoadImage:result info:info];
} else if (_delegateFlags.delegateDidLoadImage) {
ASUnlockScope(self);
Expand Down Expand Up @@ -629,7 +629,7 @@ - (void)_lazilyLoadImageIfNecessary
} else {
// First try to load the path directly, for efficiency assuming a developer who
// doesn't want caching is trying to be as minimal as possible.
auto nonAnimatedImage = [[UIImage alloc] initWithContentsOfFile:URL.path];
var nonAnimatedImage = [[UIImage alloc] initWithContentsOfFile:URL.path];
if (nonAnimatedImage == nil) {
// If we couldn't find it, execute an -imageNamed:-like search so we can find resources even if the
// extension is not provided in the path. This allows the same path to work regardless of shouldCacheImage.
Expand All @@ -642,7 +642,7 @@ - (void)_lazilyLoadImageIfNecessary
// If the file may be an animated gif and then created an animated image.
id<ASAnimatedImageProtocol> animatedImage = nil;
if (_downloaderFlags.downloaderImplementsAnimatedImage) {
auto data = [[NSData alloc] initWithContentsOfURL:URL];
let data = [[NSData alloc] initWithContentsOfURL:URL];
if (data != nil) {
animatedImage = [_downloader animatedImageWithData:data];

Expand All @@ -665,7 +665,7 @@ - (void)_lazilyLoadImageIfNecessary

if (_delegateFlags.delegateDidLoadImageWithInfo) {
ASUnlockScope(self);
auto info = [[ASNetworkImageLoadInfo alloc] initWithURL:URL sourceType:ASNetworkImageSourceFileURL downloadIdentifier:nil userInfo:nil];
let info = [[ASNetworkImageLoadInfo alloc] initWithURL:URL sourceType:ASNetworkImageSourceFileURL downloadIdentifier:nil userInfo:nil];
[delegate imageNode:self didLoadImage:self.image info:info];
} else if (_delegateFlags.delegateDidLoadImage) {
ASUnlockScope(self);
Expand All @@ -674,7 +674,7 @@ - (void)_lazilyLoadImageIfNecessary
});
} else {
__weak __typeof__(self) weakSelf = self;
auto finished = ^(id <ASImageContainerProtocol>imageContainer, NSError *error, id downloadIdentifier, ASNetworkImageSourceType imageSource, id userInfo) {
let finished = ^(id <ASImageContainerProtocol>imageContainer, NSError *error, id downloadIdentifier, ASNetworkImageSourceType imageSource, id userInfo) {
ASPerformBlockOnBackgroundThread(^{
__typeof__(self) strongSelf = weakSelf;
if (strongSelf == nil) {
Expand Down Expand Up @@ -720,7 +720,7 @@ - (void)_lazilyLoadImageIfNecessary
if (newImage) {
if (_delegateFlags.delegateDidLoadImageWithInfo) {
calloutBlock = ^(ASNetworkImageNode *strongSelf) {
auto info = [[ASNetworkImageLoadInfo alloc] initWithURL:URL sourceType:imageSource downloadIdentifier:downloadIdentifier userInfo:userInfo];
let info = [[ASNetworkImageLoadInfo alloc] initWithURL:URL sourceType:imageSource downloadIdentifier:downloadIdentifier userInfo:userInfo];
[delegate imageNode:strongSelf didLoadImage:newImage info:info];
};
} else if (_delegateFlags.delegateDidLoadImage) {
Expand All @@ -736,7 +736,7 @@ - (void)_lazilyLoadImageIfNecessary

if (calloutBlock) {
ASPerformBlockOnMainThread(^{
if (auto strongSelf = weakSelf) {
if (let strongSelf = weakSelf) {
calloutBlock(strongSelf);
}
});
Expand Down
20 changes: 10 additions & 10 deletions Source/ASRunLoopQueue.mm
Original file line number Diff line number Diff line change
Expand Up @@ -220,13 +220,13 @@ - (void)releaseObjectInBackground:(id _Nullable __strong *)objectPtr
NSParameterAssert(objectPtr != NULL);

// Cast to CFType so we can manipulate retain count manually.
auto cfPtr = (CFTypeRef *)(void *)objectPtr;
let cfPtr = (CFTypeRef *)(void *)objectPtr;
if (!cfPtr || !*cfPtr) {
return;
}

_lock.lock();
auto isFirstEntry = _queue.empty();
let isFirstEntry = _queue.empty();
// Push the pointer into our queue and clear their pointer.
// This "steals" the +1 from ARC and nils their pointer so they can't
// access or release the object.
Expand All @@ -244,9 +244,9 @@ - (void)releaseObjectInBackground:(id _Nullable __strong *)objectPtr
- (void)drain
{
_lock.lock();
auto q = std::move(_queue);
let q = std::move(_queue);
_lock.unlock();
for (auto ref : q) {
for (let ref : q) {
// NOTE: Could check that retain count is 1 and retry later if not.
CFRelease(ref);
}
Expand Down Expand Up @@ -488,11 +488,11 @@ - (void)processQueue
}

// itemsToProcess will be empty if _queueConsumer == nil so no need to check again.
auto count = itemsToProcess.size();
let count = itemsToProcess.size();
if (count > 0) {
as_activity_scope_verbose(as_activity_create("Process run loop queue batch", _rootActivity, OS_ACTIVITY_FLAG_DEFAULT));
auto itemsEnd = itemsToProcess.cend();
for (auto iterator = itemsToProcess.begin(); iterator < itemsEnd; iterator++) {
let itemsEnd = itemsToProcess.cend();
for (var iterator = itemsToProcess.begin(); iterator < itemsEnd; iterator++) {
__unsafe_unretained id value = *iterator;
_queueConsumer(value, isQueueDrained && iterator == itemsEnd - 1);
as_log_verbose(ASDisplayLog(), "processed %@", value);
Expand Down Expand Up @@ -711,11 +711,11 @@ - (void)processQueue
}

// itemsToProcess will be empty if _queueConsumer == nil so no need to check again.
auto count = itemsToProcess.size();
let count = itemsToProcess.size();
if (count > 0) {
as_activity_scope_verbose(as_activity_create("Process run loop queue batch", _rootActivity, OS_ACTIVITY_FLAG_DEFAULT));
auto itemsEnd = itemsToProcess.cend();
for (auto iterator = itemsToProcess.begin(); iterator < itemsEnd; iterator++) {
let itemsEnd = itemsToProcess.cend();
for (var iterator = itemsToProcess.begin(); iterator < itemsEnd; iterator++) {
__unsafe_unretained id value = *iterator;
[value prepareForCATransactionCommit];
as_log_verbose(ASDisplayLog(), "processed %@", value);
Expand Down
4 changes: 2 additions & 2 deletions Source/ASTableView.mm
Original file line number Diff line number Diff line change
Expand Up @@ -676,7 +676,7 @@ - (nullable NSIndexPath *)indexPathForNode:(ASCellNode *)cellNode waitingIfNeede

- (NSArray<ASCellNode *> *)visibleNodes
{
auto elements = [self visibleElementsForRangeController:_rangeController];
let elements = [self visibleElementsForRangeController:_rangeController];
return ASArrayByFlatMapping(elements, ASCollectionElement *e, e.node);
}

Expand Down Expand Up @@ -762,7 +762,7 @@ - (void)layoutSubviews
NSArray<ASCellNode *> *nodes = [_cellsForLayoutUpdates allObjects];
[_cellsForLayoutUpdates removeAllObjects];

auto nodesSizeChanged = [[NSMutableArray<ASCellNode *> alloc] init];
let nodesSizeChanged = [[NSMutableArray<ASCellNode *> alloc] init];
[_dataController relayoutNodes:nodes nodesSizeChanged:nodesSizeChanged];
if (nodesSizeChanged.count > 0) {
[self requeryNodeHeights];
Expand Down
4 changes: 2 additions & 2 deletions Source/ASTextNode.mm
Original file line number Diff line number Diff line change
Expand Up @@ -859,7 +859,7 @@ - (NSArray *)_rectsForTextRange:(NSRange)textRange measureOption:(ASTextKitRende
ASLockScopeSelf();

NSArray *rects = [[self _locked_renderer] rectsForTextRange:textRange measureOption:measureOption];
auto adjustedRects = [[NSMutableArray<NSValue *> alloc] init];
let adjustedRects = [[NSMutableArray<NSValue *> alloc] init];

for (NSValue *rectValue in rects) {
CGRect rect = [rectValue CGRectValue];
Expand Down Expand Up @@ -1308,7 +1308,7 @@ - (NSAttributedString *)_locked_prepareTruncationStringForDrawing:(NSAttributedS
NSDictionary *originalStringAttributes = [originalString attributesAtIndex:originalStringLength-1 effectiveRange:NULL];
[truncationString enumerateAttributesInRange:NSMakeRange(0, truncationString.length) options:0 usingBlock:
^(NSDictionary *attributes, NSRange range, BOOL *stop) {
NSMutableDictionary *futureTruncationAttributes = [NSMutableDictionary dictionaryWithDictionary:originalStringAttributes];
NSMutableDictionary *futureTruncationAttributes = [originalStringAttributes mutableCopy];
[futureTruncationAttributes addEntriesFromDictionary:attributes];
[truncationMutableString setAttributes:futureTruncationAttributes range:range];
}];
Expand Down
4 changes: 2 additions & 2 deletions Source/ASTextNode2.mm
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ + (ASTextLayout *)compatibleLayoutWithContainer:(ASTextContainer *)container

CGRect containerBounds = (CGRect){ .size = container.size };
{
for (auto &t : cacheValue->_layouts) {
for (let &t : cacheValue->_layouts) {
CGSize constrainedSize = std::get<0>(t);
ASTextLayout *layout = std::get<1>(t);

Expand Down Expand Up @@ -1135,7 +1135,7 @@ - (NSAttributedString *)_locked_prepareTruncationStringForDrawing:(NSAttributedS
NSDictionary *originalStringAttributes = [originalString attributesAtIndex:originalStringLength-1 effectiveRange:NULL];
[truncationString enumerateAttributesInRange:NSMakeRange(0, truncationString.length) options:0 usingBlock:
^(NSDictionary *attributes, NSRange range, BOOL *stop) {
NSMutableDictionary *futureTruncationAttributes = [NSMutableDictionary dictionaryWithDictionary:originalStringAttributes];
NSMutableDictionary *futureTruncationAttributes = [originalStringAttributes mutableCopy];
[futureTruncationAttributes addEntriesFromDictionary:attributes];
[truncationMutableString setAttributes:futureTruncationAttributes range:range];
}];
Expand Down
8 changes: 8 additions & 0 deletions Source/Base/ASBaseDefines.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@
#define AS_EXTERN FOUNDATION_EXTERN
#define unowned __unsafe_unretained

#if defined(__cplusplus)
# define var auto
# define let const auto
#else
# define var __auto_type
# define let const __auto_type
#endif

#ifdef __GNUC__
# define ASDISPLAYNODE_GNUC(major, minor) \
(__GNUC__ > (major) || (__GNUC__ == (major) && __GNUC_MINOR__ >= (minor)))
Expand Down
4 changes: 2 additions & 2 deletions Source/Details/ASBasicImageDownloader.mm
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ - (id)downloadImageWithURL:(NSURL *)URL
// cause significant performance issues.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// associate metadata with it
NSMutableDictionary *callbackData = [[NSMutableDictionary alloc] init];
let callbackData = [[NSMutableDictionary alloc] init];
callbackData[kASBasicImageDownloaderContextCallbackQueue] = callbackQueue ? : dispatch_get_main_queue();

if (downloadProgress) {
Expand All @@ -256,7 +256,7 @@ - (id)downloadImageWithURL:(NSURL *)URL
callbackData[kASBasicImageDownloaderContextCompletionBlock] = [completion copy];
}

[context addCallbackData:[NSDictionary dictionaryWithDictionary:callbackData]];
[context addCallbackData:[[NSDictionary alloc] initWithDictionary:callbackData]];

// Create new task if necessary
NSURLSessionDownloadTask *task = (NSURLSessionDownloadTask *)[context createSessionTaskIfNecessaryWithBlock:^(){return [_session downloadTaskWithURL:URL];}];
Expand Down
2 changes: 1 addition & 1 deletion Source/Details/ASCollectionLayoutState.mm
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ - (UICollectionViewLayoutAttributes *)layoutAttributesForElement:(ASCollectionEl
}

// Use a set here because some items may span multiple pages
auto result = [[NSMutableSet<UICollectionViewLayoutAttributes *> alloc] init];
let result = [[NSMutableSet<UICollectionViewLayoutAttributes *> alloc] init];
for (id pagePtr in pages) {
ASPageCoordinate page = (ASPageCoordinate)pagePtr;
NSArray<UICollectionViewLayoutAttributes *> *allAttrs = [_pageToLayoutAttributesTable objectForPage:page];
Expand Down
10 changes: 5 additions & 5 deletions Source/Details/ASDataController.mm
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ - (void)_layoutNode:(ASCellNode *)node withConstrainedSize:(ASSizeRange)constrai
return @[];
}

auto indexPaths = [[NSMutableArray<NSIndexPath *> alloc] init];
let indexPaths = [[NSMutableArray<NSIndexPath *> alloc] init];
if ([kind isEqualToString:ASDataControllerRowNodeKind]) {
std::vector<NSInteger> counts = [self itemCountsFromDataSource];
[sections enumerateRangesUsingBlock:^(NSRange range, BOOL * _Nonnull stop) {
Expand Down Expand Up @@ -671,7 +671,7 @@ - (void)updateWithChangeSet:(_ASHierarchyChangeSet *)changeSet
[layoutDelegateClass calculateLayoutWithContext:layoutContext];
completion();
} else {
auto elementsToProcess = [[NSMutableArray<ASCollectionElement *> alloc] init];
let elementsToProcess = [[NSMutableArray<ASCollectionElement *> alloc] init];
for (ASCollectionElement *element in newMap) {
ASCellNode *nodeIfAllocated = element.nodeIfAllocated;
if (nodeIfAllocated.shouldUseUIKitCell) {
Expand Down Expand Up @@ -827,10 +827,10 @@ - (void)relayoutNodes:(id<NSFastEnumeration>)nodes nodesSizeChanged:(NSMutableAr
}

id<ASDataControllerSource> dataSource = self.dataSource;
auto visibleMap = self.visibleMap;
auto pendingMap = self.pendingMap;
let visibleMap = self.visibleMap;
let pendingMap = self.pendingMap;
for (ASCellNode *node in nodes) {
auto element = node.collectionElement;
let element = node.collectionElement;
NSIndexPath *indexPathInPendingMap = [pendingMap indexPathForElement:element];
// Ensure the element is present in both maps or skip it. If it's not in the visible map,
// then we can't check the presented size. If it's not in the pending map, we can't get the constrained size.
Expand Down
Loading

0 comments on commit 55abeed

Please sign in to comment.