castwide / solargraph

A Ruby language server.
https://solargraph.org
MIT License
1.87k stars 154 forks source link

Conversion between dashes in gemspec name and slashes in required paths #697

Open kosuke-suzuki opened 7 months ago

kosuke-suzuki commented 7 months ago

I was faced with a strange behavior and finally found the possible root cause of it.

Background

As recommended by Rubygems.org "Name your gem", there is a conventional correspondence between dashes - in a gem name and slashes / in a required path.

For example, if you want to use net-smtp gem, first you have to add to your Gemfile

gem "net-smtp"

and second you require it:

require "net/smtp"

# Do anything fancy with Net::SMTP
Net::SMTP.start('127.0.0.1')

Problem

However, I noticed that solargraph did not suggest to me the source code comments on net-smtp. In the code above I expected solargraph to show me the signature of Net::SMTP.start() but it did not.

I found that the root cause of this phenomenon was how solargraph treated required paths. Currently it regards the first part of slash-separated required path as the name of the gem. https://github.com/castwide/solargraph/blob/master/lib/solargraph/yard_map.rb#L285

name = path.split('/').first.to_s

Therefore, when it finds

require "net/smtp"

sentence, the regarded gem name is not net-smtp but net.

So there is no way for solargraph to detect gems whose names are dash-concatenated and whose actual relative paths are NOT dash-concatenated but slash-separated.

Proposal

Here I propose another algorithm to determine the name of the gem.

  1. Split the required path by slashes /
  2. Concatenate all by dashes - and let it be the candidate of the name of the gem
  3. Check if there is such gem
  4. If it exists, it is the actual name of such gem. If it does not, omit the last part of the dashes and go back to step 3

For example, with this algorithm, when solargraph encounters the line

require "net/smtp/authenticator"
  1. ["net", "smtp", "authenticator"]
  2. net-smtp-authenticator
  3. Does the gem with name net-smtp-authenticator exist? No it does not.
  4. Does the gem with name net-smtp exists? Yes it does.

After I applied this algorithm to my environment, solargraph showed me source code comments in Net::SMTP as I expected.

Any possible drawbacks?