Configuring YCM and `rust-analyzer` to work with standalone files
Closed this issue · 2 comments
I was surprised to find that, unlike gopls
or other code completion engines I've worked with, rust-analyzer
does not work with standalone files. (For example, it fails unceremoniously with a 'rust-analyzer failed to discover workspace' error if there's no Cargo project and Cargo.toml
file.) I managed to configure this by integrating information from both the rust-analyzer
and YCM documentation. I wanted to share this information; if there's a suitable place in the documentation for it, please let me know. Otherwise, feel free to close this issue, in the hope that it will assist others facing the same problem.
# Configuration script for rust-analyzer to work with standalone files
import subprocess
def GetRustSysroot():
result = subprocess.check_output( [ 'rustc', '--print', 'sysroot' ], encoding='utf-8' )
return result.strip()
def IsCargoPackage() -> bool:
result = subprocess.run( [ 'cargo', 'pkgid' ] )
return result.returncode == 0
def Settings( **kwargs ):
if kwargs[ 'language' ] == 'rust':
if IsCargoPackage():
return {} # use Cargo.toml autodiscovery
# Treat current file as a standalone package
try:
sysroot = GetRustSysroot()
except subprocess.CalledProcessError:
return {}
file = kwargs['filename']
return {
'ls': {
'linkedProjects': [
{
"sysroot": sysroot,
"crates": [
{
"root_module": file,
"edition": "2021",
"deps": []
},
],
},
]
},
}
Thank you for sharing the info.
The easiest way to contr8bute this kind of info is to create a new page on the wiki, which is community maintained.
I am h9nestly not sure how often peopoe need a rust file without a cargo toml. It might also be worth adding a sentence or two to the readme. Maybe just pointing to the documentation of linkedProjects
?
Lastly, if we want to catch RA regressions regarding working with standalone foles, we wpuld need tests. That wau, the next time someone tries to update thenightly ycmd uses for rust support, a test might fail in case of RA regression. Probably an overkill.
unlike gopls
Huh... I remember a time where gopls only kind of supported standalone files. It would try, but not very hard. Maybe things have changed.
Thanks. I added this to the Wiki:
https://github.com/ycm-core/YouCompleteMe/wiki/Rust-Completion-with-Standalone-Files
If other people encounter this and find it useful, I'll add a link to the README.