Unused import tool

Basile B. b2.temp at gmx.com
Wed Aug 16 05:26:11 UTC 2023


On Tuesday, 15 August 2023 at 08:13:04 UTC, RazvanN wrote:
> Hello everyone,
>
> I have started working on [a tool that identifies unused 
> imports](https://github.com/RazvanN7/Unused-Import/tree/master). It uses dmd as a library.
>
> The purpose is to have a working tool, but also to better 
> understand what sort of information the frontend needs to 
> output so that such tools are possible.
>
> Up to this point, I managed to make it work with global imports 
> (since dmdfe currently does not provide the scope hierarchy).

You can handle nested import declarations without the scope. The 
trick would be to use a single visitor and a 2D import list, 
i.e`ImportInfo[][] imports;`. The first dim matches to a scope, 
so when you enter a scope (BlockStmt, AggrDecl, etc) you push the 
local imports, and when you leave the scope, you check and pop. 
Styx 
[Example](https://gitlab.com/styx-lang/styx/-/blob/master/src/styx/lint.sx?ref_type=heads#L247), (which has same semantics as D about out-of-order decls).

> The tool does output some false positives because semantic is 
> destructive and some things like aliases or enums are 
> substituted eagerly and you cannot trace their origin.

This is why I think that such a tool should be integrated to the 
compiler.

The only way (I know of today) to detect accurately whether an 
alias is used is to put of flag in the ast node matching to 
imports. For dmd that flag would be set in `Import.search()`.

> I have tested this tool with some dmd sources and have already 
> identified [unused 
> imports](https://github.com/dlang/dmd/pulls?q=is%3Apr+delete+unused+imports+author%3ARazvanN7+is%3Aopen>
> So, if you have projects with lots of global imports you could 
> use it to at least narrow down the list of potential unused 
> imports.
>
> The tool is a work in progress, so if you have any ideas for 
> improvement feel free to ping me.
>
> Note that the import paths used are from my machine, so you 
> will need to update those accordingly to the files imported in 
> your project.

Again another reason to integrate the tool to the compiler. There 
would be no need to write a driver, just a new option, let's say 
"--check-unused-import", and "basta".

Also I see no use case where the tool would be used with 
different import paths than those passed to the compiler.

>
> RazvanN




More information about the Digitalmars-d mailing list