rust_analyzer_modules/
utils.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5use ra_ap_syntax::ast;
6
7use anyhow::bail;
8
9pub fn sanitized_use_tree(
10    focus_on: Option<&str>,
11    crate_name: &str,
12) -> anyhow::Result<ast::UseTree> {
13    let mut path_expr = focus_on.unwrap_or(crate_name).to_owned();
14
15    // Trim leading `::` from `use` expression,
16    // expressions are implied to be absolute:
17    let double_colon_prefix = "::";
18    if path_expr.starts_with(double_colon_prefix) {
19        let range = 0..(double_colon_prefix.len() - 2);
20        path_expr.replace_range(range, "");
21    }
22
23    let crate_prefix = "crate::";
24    if path_expr.starts_with(crate_prefix) {
25        let range = 0..(crate_prefix.len() - 2);
26        path_expr.replace_range(range, crate_name);
27    }
28
29    for keyword in ["super", "self", "$crate"] {
30        let keyword_prefix = format!("{keyword}::");
31
32        if path_expr == keyword || path_expr.starts_with(&keyword_prefix) {
33            bail!("unexpected keyword `{keyword}` in `--focus-on` option");
34        }
35    }
36
37    Ok(crate::analyzer::parse_use_tree(&path_expr))
38}