Skip to content

Commit

Permalink
Merge pull request #181 from typelevel/as-unit-to-void
Browse files Browse the repository at this point in the history
Linter for `.as(())` => `.void`
  • Loading branch information
armanbilge authored Dec 18, 2024
2 parents 914f7ec + da98dc1 commit 6b86461
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
9 changes: 9 additions & 0 deletions modules/cats/input/src/main/scala/fix/AsTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ rule = TypelevelAs
*/
package fix

import cats.syntax.functor.toFunctorOps

object AsTests {

def listMapLit = {
Expand All @@ -17,11 +19,18 @@ object AsTests {
.map(_ => ()) can be replaced by .void */
}

def listAsUnit = {
List(1, 2, 3).as(()) /* assert: TypelevelAs.as
^^^^^^^^^^^^^^^^^^^^
.as(()) can be replaced by .void */
}

def shouldBeIgnored = {
def f = "a"
List(1, 2, 3).map(_ => f)
List(1, 2, 3).map(i => i)
List(1, 2, 3).map(println(_))
List(1, 2, 3).as(1)
}

}
19 changes: 19 additions & 0 deletions modules/cats/rules/src/main/scala/org/typelevel/fix/As.scala
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ class As extends SemanticRule("TypelevelAs") {
case tree @ AnonymousMap(Lit.Unit()) => Patch.lint(VoidDiagnostic(tree))
// fa.map(_ => 1)
case tree @ AnonymousMap(_: Lit) => Patch.lint(AsDiagnostic(tree))
// fa.as(())
case tree @ As(Lit.Unit()) => Patch.lint(AsUnitDiagnostic(tree))
}.asPatch

}
Expand All @@ -41,6 +43,17 @@ object AnonymousMap {
}
}

object As {
def unapply(term: Term): Option[Term] = term match {
case Term.Apply.Initial(
Term.Select(_, Term.Name("as")),
List(value)
) =>
Some(value)
case _ => None
}
}

final case class AsDiagnostic(t: Tree) extends Diagnostic {
override def message: String = ".map(_ => f) can be replaced by .as(f)"
override def position: Position = t.pos
Expand All @@ -52,3 +65,9 @@ final case class VoidDiagnostic(t: Tree) extends Diagnostic {
override def position: Position = t.pos
override def categoryID: String = "as"
}

final case class AsUnitDiagnostic(t: Tree) extends Diagnostic {
override def message: String = ".as(()) can be replaced by .void"
override def position: Position = t.pos
override def categoryID: String = "as"
}

0 comments on commit 6b86461

Please sign in to comment.