Scala tool to remove all unused code
Asked Answered
S

3

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.

Scincoid answered 9/3, 2016 at 22:12 Comment(2)
The closest thing I know is to use -Ywarn-unused and -Ywarn-unused-import as sbt options.Lithograph
Possible duplicate of Is there a tool for Scala to clean all the unused imports from all the code files?Allow
H
1

Scalafix has a rewrite for this: RemoveUnusedImports

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

Hefner answered 28/7, 2017 at 0:29 Comment(0)
B
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.

Blank answered 8/8, 2016 at 9:55 Comment(0)
H
1

Scalafix has a rewrite for this: RemoveUnusedImports

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

Hefner answered 28/7, 2017 at 0:29 Comment(0)
C
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.

Carnatic answered 16/9, 2016 at 18:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.