Skip to content

Commit

Permalink
FormatTokens: define a token hash builder
Browse files Browse the repository at this point in the history
  • Loading branch information
kitbellew committed Jul 6, 2024
1 parent f042232 commit c662742
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ class FormatTokens(leftTok2tok: Map[TokenHash, Int])(val arr: Array[FormatToken]
extends IndexedSeq[FormatToken] {

private def this(arr: Array[FormatToken]) = this {
val result = Map.newBuilder[TokenHash, Int]
val result = new FormatTokens.TokenToIndexMapBuilder
result.sizeHint(arr.length)
arr.foreach(t => result += FormatTokens.thash(t.left) -> t.meta.idx)
result += FormatTokens.thash(arr.last.right) -> arr.last.meta.idx
arr.foreach(t => result.add(t.meta.idx)(t.left))
result.add(arr.last.meta.idx)(arr.last.right)
result.result()
}(arr)

Expand Down Expand Up @@ -363,4 +363,11 @@ object FormatTokens {
@inline
def thash(token: Token): TokenHash = hash(token)

class TokenToIndexMapBuilder {
private val builder = Map.newBuilder[TokenHash, Int]
def sizeHint(size: Int): Unit = builder.sizeHint(size)
def add(idx: Int)(token: Token): Unit = builder += thash(token) -> idx
def result(): Map[TokenHash, Int] = builder.result()
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import org.scalafmt.config.ScalafmtConfig
import org.scalafmt.internal.FormatToken
import org.scalafmt.internal.FormatTokens
import org.scalafmt.util.StyleMap
import org.scalafmt.util.TokenOps

import scala.meta.Tree
import scala.meta.tokens.{Token => T}
Expand Down Expand Up @@ -37,7 +36,7 @@ class FormatTokensRewrite(
val result = Array.newBuilder[FormatToken]
result.sizeHint(arr.length)

val tokenMap = Map.newBuilder[TokenOps.TokenHash, Int]
val tokenMap = new FormatTokens.TokenToIndexMapBuilder
tokenMap.sizeHint(arr.length)

val shiftedIndexMap = mutable.Map.empty[Int, Int]
Expand All @@ -64,7 +63,7 @@ class FormatTokensRewrite(
@inline
def mapOld(dstidx: Int) = {
remapped = true
tokenMap += FormatTokens.thash(rtOld) -> dstidx
tokenMap.add(dstidx)(rtOld)
}

copySlice(idx)
Expand Down Expand Up @@ -115,14 +114,14 @@ class FormatTokensRewrite(
}
val newMeta = ft.meta.copy(idx = idx, left = leftMeta)
newarr(idx) = ft.copy(left = left, meta = newMeta)
tokenMap += FormatTokens.thash(left) -> idx
tokenMap.add(idx)(left)
iter(idx + 1)
}
iter(0)

tokenMap += {
locally {
val ft = newarr.last
FormatTokens.thash(ft.right) -> ft.meta.idx
tokenMap.add(ft.meta.idx)(ft.right)
}
new FormatTokens(tokenMap.result())(newarr)
}
Expand Down

0 comments on commit c662742

Please sign in to comment.