13

I am writing a Scala plugin for an editor I use that would highlight all unused code paths (could be unused defs, vals, classes and implicits), and give the user an option to yank them out of the .scala file.

How can I do this? To simplify the problem, let's pretend we only have a single root level .scala file with no external dependency on libraries or any other code files.

Ideally I would want this to be an SBT plugin that, given a single such Foo.scala file, would spit out Foo_min.Scala file with all unused code removed.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
pathikrit
  • 32,469
  • 37
  • 142
  • 221
  • 2
    The closest thing I know is to use `-Ywarn-unused` and `-Ywarn-unused-import` as sbt options. – Ende Neu Mar 09 '16 at 22:42
  • Possible duplicate of [Is there a tool for Scala to clean all the unused imports from all the code files?](https://stackoverflow.com/questions/7767567/is-there-a-tool-for-scala-to-clean-all-the-unused-imports-from-all-the-code-file) – Guillaume Massé Oct 09 '17 at 13:01

3 Answers3

4

You need some kind of semantic API to traverse over the code and ask questions like "is this variable/import ever used" ?

As far as I know, Intellij uses Meta programming System to achieve same goals. For scala, you can wait for scalameta's 2.0 release, which (most probably) will support semantic API.

dveim
  • 3,381
  • 2
  • 21
  • 31
1

Scalafix has a rewrite for this: RemoveUnusedImports

Follow those instructions to run it: https://scalacenter.github.io/scalafix/#Installation

Guillaume Massé
  • 8,004
  • 8
  • 44
  • 57
0

You're basically looking for a callgraph.

A complete but complex callgraph for Scala code is implemented in the Dotty Linker. This is state of the art. However, even building an easier callgraph is not a trivial task. I wouldn't be surprised if a Meta implementation would be constrained to perform such a task. Particularly, you need to be very careful with implicits and scoping, especially given the fact that meta macros are expanded after typer.

Creating your own callgraph requires symbols, types and implicit searches. I'm afraid you need to wait until the Semantic API in Scala Meta 2.0 is released.

Jorge
  • 784
  • 4
  • 17