scala-purrism
Scalafix semantic rules for teams moving real Scala code toward Typelevel, Cats, and Cats Effect idioms.
It is for codebases that already use cats, cats-effect, or tagless-final
style, but still carry concrete collection types, hand-written effect plumbing,
manual Either/Option branches, or local helpers that duplicate Cats APIs.
The rules make those migrations repeatable: they rewrite code, type-check the
result through SemanticDB, and avoid broad signature changes unless the
configured rule can see enough call-site context.
Use it when you need to:
- weaken concrete effect constraints such as
Syncto the smallest Cats typeclass that the method actually needs - generalize
List/Vector/Optionsignatures into polymorphic collection or typeclass APIs - replace local boilerplate with standard Cats syntax and functions
- reshape callback-style and environment-threading code into
KleisliorArrowforms where that improves the program shape - propagate opaque domain types from selected seed fields through assignments and calls
It is intentionally conservative. Rules decline when the rewrite would require unsafe public API changes, unseen cross-file call-site edits, missing Cats evidence, or behavior changes that are not explicitly enabled.
The examples below are compiled with mdoc. Diff blocks show the exact code shape each rule rewrites, and the resulting examples are type-checked against Cats and Cats Effect.
Setup
Add the published rule artifact:
io.github.mercurievv:scala-purrism-scalafix_3:0.9.0
Enable SemanticDB in the target project:
scalacOptions += "-Ysemanticdb"
Choose rules in .scalafix.conf:
Configs:
rules = [
TypelevelPurrism // [required] umbrella rule set
]
For whole-project rewrites, run Scalafix over every relevant source file and pass every SemanticDB target root. Recompile between stages when one rule changes signatures that another rule reads semantically.
Every lint prints a coded id ([Rule.kind]) with a repair instruction —
see Findings for the full table.
Rule Sets
TypelevelPurrism
Runs TypeclassWeakening, PreferKleisli, PreferArrow,
PreferTypeParameters, and PreferCatsExpressions.
Configs:
rules = [ TypelevelPurrism ] // [required] run the full recommended rule set
Since 0.8.0 the widening member is PreferTypeParameters — all three of
PreferPolymorphicCollectionOps, PreferPolymorphicCollections and
PreferPolymorphicTypeclasses — where it was PreferPolymorphicTypeclasses alone. Every
member key reaches them through the umbrella:
Configs:
PreferArrow.aggressive = true // [optional] enable broader Arrow rewrites
PreferPolymorphicTypeclasses.widenPublic = true // [optional] allow public signature changes
PreferPolymorphicCollections.crossFile = true // [optional] inspect references across files
PreferPolymorphicCollectionOps.rewrite = false // [optional] keep signature widening, skip body rewrites
PreferPolymorphicCollectionOps is the one member that rewrites a body:
mkString becomes mkString_, which renders elements with Show rather than
toString. Where the two disagree the program prints something different. Set
PreferPolymorphicCollectionOps.rewrite = false to keep the umbrella's widenings
purely at the signature.
PreferTypeParameters
Runs the three signature-widening rules together:
PreferPolymorphicCollectionOps, PreferPolymorphicCollections, and
PreferPolymorphicTypeclasses.
Configs:
rules = [ PreferTypeParameters ] // [required] run all signature-widening rules
def labels[A, S[_]: Functor](values: ListS[A]): ListS[String] =
values.map(_.toString)
val out = labels[Int](List(1, 2))
PreferCatsExpressions
Runs PreferCatsFunctions, PreferCatsSyntax, and SimplifyCatsExpressions
together — see Cats Expressions below for how they
differ.
Configs:
rules = [ PreferCatsExpressions ] // [required] run all three expression rules
Expression And Data Idioms
Local rewrites inside method bodies. These rules improve Cats usage, remove manual collection plumbing, or make data flow more explicit without changing the broad program architecture.
Cats Expressions
PreferCatsExpressions runs three rules that all move an expression toward
the Cats API, each on a different tree shape:
| rule | shape it matches |
|---|---|
PreferCatsFunctions |
a whole method body, against an index of known Cats source functions |
PreferCatsSyntax |
a summoner call — Typeclass[F].method(fa) |
SimplifyCatsExpressions |
a dot-syntax sub-expression already in that shape, e.g. fa.map(_ => ()) |
def lifted[F[_]: Applicative, A](a: A): F[A] =
Applicative[F].pure(a)
a.pure[F]
val cleared = lifted[Option, Unit](()).map(_ => ())void
lifted's body → PreferCatsFunctions (whole-body match against the index,
which happens to render as the same call PreferCatsSyntax would produce
here). cleared → SimplifyCatsExpressions (.map(_ => ()) → .void).
Configs: none.
Data And Collection Flow
PropagateOpaqueType
Introduces an opaque type and follows selected SemanticDB seed symbols through value flow.
Examples:
final case class Task(branchName: StringBranchName)
def checkout(branchName: String): IO[Unit] =
IO.println(branchName)
Configs:
PropagateOpaqueType.types = [ // [required for explicit propagation] opaque types to introduce
{
name = "BranchName" // [required] new opaque type name
underlying = "scala/Predef.String#" // [optional] SemanticDB symbol for the representation
definitionFile = "Task.scala" // [required] file where the opaque type is generated
seeds = [ "_empty_/Task#branchName." ] // [required] starting symbols for value-flow propagation
widen = [] // [optional] symbols allowed to keep the underlying type
}
]
PropagateOpaqueType.autoDiscover.enabled = false // [optional] require explicit seed config
PreferOptionIdioms
Rewrites nullable lookup and Option.map(...).getOrElse(...) shapes.
Examples:
def test[A, B](option: Option[A], render: A => B, default: B) =
option.map(render).getOrElse(default)
option.fold(default)(render)
def test[A](value: A) =
if value == null then None else Some(value)
Configs:
PreferOptionIdioms.rewrite = true // [optional] apply Option idiom rewrites
PreferOptionIdioms.mouse = false // [optional] do not use mouse syntax helpers
PreferIndexedMap
Rewrites index loops to direct collection operations, and effectful left folds
to foldM.
Examples:
def test(xs: List[Int]) =
xs.indices.map(i => xs(i)map(x => x.toString)
def test(xs: List[Int]) =
xs.zipWithIndex.map { case (x, i) => s"$i:$x" }
Configs:
PreferIndexedMap.rewrite = true // [optional] rewrite index-based loops when safe
Effectful Program Shape
Rules that alter how effects, side effects, and effectful data-in/data-out flows are represented. These rewrites usually affect control-flow shape more than individual expressions.
Effect Boundaries
TypeclassWeakening
Weakens a context bound to the single weakest typeclass the body still
satisfies, intermediate typeclasses included (flatMap only gives FlatMap,
not Monad). Capabilities are read from the compiler: direct calls, syntax
conversions such as toFlatMapOps, and the evidence the compiler passes on.
Library typeclass facts (cats and cats-effect) come from the TASTy of the jars
on the scalac classpath, so the rule needs a semantic classpath to act.
The bound is kept as written when the rule cannot be sure, in these cases:
- no classpath or no typeclass index is available (nothing to read the library typeclasses from);
- the def is overridable or overrides another def, so its signature is a contract;
- the body uses a summoner such as
Sync[F], or uses named evidence ([F[_]: Sync as S]) other than as the qualifier of a capability call; - the body passes implicit evidence to a method whose signature is unknown;
- the typeclass is defined in the project's own sources (only classpath typeclasses are indexed);
- several equally weak typeclasses fit (the choice is ambiguous), which is
reported as the lint
TypeclassWeakening.ambiguous-weakening; - the type parameter holds more than one evidence (
F[_]: Temporal: Sync, or a bound next to ausing/implicitparameter mentioningF): all of its bounds are kept, since weakening each alone could produce two identical or competing instances; - a call of the def in the same file runs where two or more in-scope
evidences for the type argument descend from the weakened typeclass
(
bump(fa)inside[F[_]: Temporal: Sync]would find twoFunctor[F]); - the target's simple name already means something else in the file (a local
trait Functor, another library'sFunctorimported explicitly); - under
TypelevelPurrism, another member (PreferKleisli,PreferArrow) rewrites the same def or Kleisli body; - under
TypelevelPurrism,PreferTypeParametersbuilds on the type parameter: it reuses it for a widenedList/Optionuse (relying on its bound as written, e.g.Traversefor a movedfoldLeft), or appends a new type parameter right after it.
Known risk: the rule sees one file at a time. A caller in another file whose
scope holds two evidences descending from the weakened typeclass (for
example [F[_]: Temporal: Sync] calling a bump now bounded by Functor)
gets an "Ambiguous given instances" error there. Pass the evidence explicitly
or revert that bound.
Two-parameter typeclasses render through their aliases (MonadThrow,
ApplicativeThrow, MonadCancelThrow). A tagless algebra such as
profiles: Profiles[F] is an ordinary value and does not block weakening.
Examples:
def bump[F[_]: SyncFunctor](fa: F[Int]): F[Int] =
fa.map(_ + 1)
def choose[F[_]: ConcurrentApplicativeThrow, A](left: F[A], right: F[A]): F[A] =
left.handleErrorWith(_ => right)
def orZero[F[_]: SyncApplicativeThrow](fa: F[Int]): F[Int] =
fa.handleError(_ => 0)
def twice[F[_]: SyncFlatMap](fa: F[Int], next: Int => F[Int]): F[Int] =
fa.flatMap(next)
Configs:
TypeclassWeakening {
cacheDir = "~/.cache/scala-purrism/tasty-index" # "" disables the disk cache
debug = false # log index source, jars scanned and time to stderr
}
The first run scans library jars and stores one index row per jar in
cacheDir; later runs read it from disk. With debug = true each jar
reports Bundled, Disk or Scan and the milliseconds spent.
Supported range: the bundled index covers only cats-core and cats-kernel 2.13.0. Any other cats version, cats-effect, and every other library are scanned from the TASTy on the classpath, so results can differ by library version. The rule is built and tested with Scala 3.8 (TASTy 3.8). Newer TASTy the bundled reader cannot decode, or an incompatible classpath, makes the index unavailable, and then the rule keeps every bound and changes nothing.
SuspendSideEffects
Reports side effects that a signature does not mention and rewrites eager
pure(effect) into suspended delay(effect) where an effect type supports it.
Examples:
def test[F[_]: Sync] =
Sync[F].puredelay(System.nanoTime())
def read[F[_]: Sync](path: Path): F[String] =
Sync[F].puredelay(Files.readString(path))
Configs:
SuspendSideEffects.rewrite = true // [optional] rewrite eager pure(effect) into delay(effect)
SuspendSideEffects.report = true // [optional] report side effects that cannot be rewritten
SuspendSideEffects.effects = [ "IO", "SyncIO", "Resource", "Stream", "Task", "EitherT", "OptionT", "Kleisli" ] // [optional] effect types to inspect
PreferEffectIdioms
Rewrites decidable effect idioms and reports shapes that need a wider program decision.
Examples:
def test[A](work: () => A, fallback: () => A) =
try work()
catch { case _: ThrowableNonFatal(_) => fallback() }
def test(open: () => Unit, close: () => Unit) =
try open()
finally close()
Configs:
PreferEffectIdioms.rewrite = true // [optional] apply decidable rewrites
PreferEffectIdioms.resources = true // [optional] suggest Resource for acquire/release shapes
PreferEffectIdioms.refs = true // [optional] inspect mutable reference idioms
Kleisli And Arrow
PreferKleisli
Turns effectful data-in/data-out methods into Kleisli values and re-splits
direct call sites.
Examples:
def load[F[_]: Monad](id: Long): F[: Kleisli[F, Long, String] =
Kleisli.apply { id =>
id.toString.pure[F]
}
val loaded: IO[String] = load[IO](42)
def save[F[_]: Monad](name: String): F[: Kleisli[F, String, Unit] =
Kleisli.apply { name =>
name.trim.pure[F].void
}
val saved: IO[Unit] = save[IO](" Ada ")
Configs:
PreferKleisli.fileLocalOnly = false // [optional] update call sites outside the defining file
PreferKleisli.crossFile = true // [optional] inspect references across files
PreferKleisli.crossFileRoot = "." // [optional] project root for cross-file lookup
PreferArrow
Rewrites hand-threaded Kleisli bodies into Arrow composition such as >>>,
.map, and &&&.
Examples:
def test[F[_]: Functor](load: Kleisli[F, Long, String]) =
Kleisli { (id: Long) => load.run(id).map(_.trim) }
load.map(_.trim)
def test[F[_]: Monad](load: Kleisli[F, Long, String], validate: Kleisli[F, String, String]) =
Kleisli { (id: Long) => load.run(id).flatMap(validate.run) }
Configs:
PreferArrow.aggressive = false // [optional] keep rewrites conservative
PreferArrow.reportSkips = false // [optional] omit diagnostics for declined rewrites
Polymorphic API Shape
Signature-level rules that generalize concrete APIs to type parameters. They need broader semantic confidence because they can change method boundaries and call sites, not only local expressions.
Polymorphic Signatures
Three rules widen one concrete type constructor in a signature to a type parameter, each over a different subject — never the same parameter twice:
| rule | subject | touches the body? |
|---|---|---|
PreferPolymorphicTypeclasses |
any unary constructor Cats has — Eval, Show, Option, domain types — except collections |
no |
PreferPolymorphicCollections |
List/Seq/Vector/... (containers) |
no |
PreferPolymorphicCollectionOps |
same collections, only bodies calling mkString/sum-like ops |
yes — renames the call too, e.g. mkString → mkString_ |
One file, one method per rule, run through the umbrella PreferTypeParameters:
Examples:
final class Summary {
private def names[S[_]: Functor](users: ListS[String]): ListS[String] =
users.map(user => user.toUpperCase)
private def rendered[S[_]: Foldable](rows: ListS[String]): String =
rows.mkString_("[", ",", "]")
private def duplicate[G[_]: Comonad](e: EvalG[Int]): EvalG[Int] =
e.coflatMap(w => w.extract + 1)
}
names → PreferPolymorphicCollections. rendered → PreferPolymorphicCollectionOps
(signature and the call). duplicate → PreferPolymorphicTypeclasses (not a collection).
Configs:
PreferPolymorphicTypeclasses.containers = [ "List", "Seq", "Vector", "IndexedSeq", "LazyList" ] // [optional] exclude collection constructors from this rule
PreferPolymorphicTypeclasses.widenPublic = false // [optional] keep public APIs unchanged
PreferPolymorphicTypeclasses.maxConstraints = 2 // [optional] cap added typeclass constraints
PreferPolymorphicCollections.containers = [ "List", "Seq", "Vector", "IndexedSeq", "LazyList" ] // [optional] collection constructors eligible for widening
PreferPolymorphicCollections.widenPublic = false // [optional] keep public APIs unchanged
PreferPolymorphicCollections.maxConstraints = 2 // [optional] cap added typeclass constraints
PreferPolymorphicCollectionOps.containers = [ "List", "Seq", "Vector", "IndexedSeq", "LazyList" ] // [optional] collection constructors eligible for body-aware widening
PreferPolymorphicCollectionOps.elements = [ "String", "Int", "Long", "Double", "Boolean", "..." ] // [optional] element types with supported ops
PreferPolymorphicCollectionOps.rewrite = true // [optional] also rewrite affected body calls
All three also take rewrite, crossFile, and crossFileTargetroots.
Cross-File Keys
The signature-widening rules read these keys from their own config block:
Configs:
PreferPolymorphicCollections.crossFile = true // [optional] inspect references across files
PreferPolymorphicCollections.crossFileRoot = "." // [optional] project root for cross-file lookup
PreferPolymorphicCollections.crossFileTargetroots = [ "out" ] // [optional] SemanticDB target roots
Use crossFileTargetroots = [ "target" ] for sbt-style output, or ["out"]
for Mill-style output. Compile first; stale SemanticDB means stale decisions.
More
- Engineering rules
- Golden fixtures
- Prefer Cats Functions contract
- RestrictVocabulary design spec
- Kleisli to Arrow catalogue
- Publishing