Skip to content

Commit

Permalink
Merge pull request #123 from norio-nomura/use-lazy-in-comment-range-b…
Browse files Browse the repository at this point in the history
…efore-offset

Optimize `SyntaxMap.commentRangeBeforeOffset(_:)`
  • Loading branch information
jpsim committed Dec 15, 2015
2 parents 32ff5ce + c36f505 commit 6346b52
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions Source/SourceKittenFramework/SyntaxMap.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,23 @@ public struct SyntaxMap {
- parameter offset: Last possible byte offset of the range's start.
*/
public func commentRangeBeforeOffset(offset: Int) -> Range<Int>? {
let tokensBeforeOffset = tokens.filter { $0.offset < offset }
let commentTokensImmediatelyPrecedingOffset = filterLastContiguous(tokensBeforeOffset) { token in
SyntaxKind.docComments().map({$0.rawValue}).contains(token.type)
}

// be lazy for performance
let tokensBeforeOffset = tokens.lazy.reverse().filter { $0.offset < offset }

let docTypes = SyntaxKind.docComments().map({$0.rawValue})
let isDoc = { (token: SyntaxToken) -> Bool in docTypes.contains(token.type) }
let isNotDoc = { !isDoc($0) }

guard let commentBegin = tokensBeforeOffset.indexOf(isDoc) else { return nil }
let tokensBeginningComment = tokensBeforeOffset.suffixFrom(commentBegin)

// For avoiding declaring `var` with type annotation before `if let`, use `map()`
let commentEnd = tokensBeginningComment.indexOf(isNotDoc)
let commentTokensImmediatelyPrecedingOffset = (
commentEnd.map(tokensBeginningComment.prefixUpTo) ?? tokensBeginningComment
).reverse()

return commentTokensImmediatelyPrecedingOffset.first.flatMap { firstToken in
return commentTokensImmediatelyPrecedingOffset.last.map { lastToken in
return Range(start: firstToken.offset, end: lastToken.offset + lastToken.length)
Expand Down

0 comments on commit 6346b52

Please sign in to comment.