<commit_before>//! FIXME: write short doc here

use hir::{HirDisplay, SourceAnalyzer, SourceBinder};
use once_cell::unsync::Lazy;
use ra_ide_db::RootDatabase;
use ra_prof::profile;
use ra_syntax::{
    ast::{self, ArgListOwner, AstNode, TypeAscriptionOwner},
    match_ast, SmolStr, SourceFile, SyntaxKind, SyntaxNode, TextRange,
};

use crate::{FileId, FunctionSignature};

#[derive(Debug, PartialEq, Eq)]
pub enum InlayKind {
    TypeHint,
    ParameterHint,
}

#[derive(Debug)]
pub struct InlayHint {
    pub range: TextRange,
    pub kind: InlayKind,
    pub label: SmolStr,
}

pub(crate) fn inlay_hints(
    db: &RootDatabase,
    file_id: FileId,
    file: &SourceFile,
    max_inlay_hint_length: Option<usize>,
) -> Vec<InlayHint> {
    let mut sb = SourceBinder::new(db);
    let mut res = Vec::new();
    for node in file.syntax().descendants() {
        get_inlay_hints(&mut res, &mut sb, file_id, &node, max_inlay_hint_length);
    }
    res
}

fn get_inlay_hints(
    acc: &mut Vec<InlayHint>,
    sb: &mut SourceBinder<RootDatabase>,
    file_id: FileId,
    node: &SyntaxNode,
    max_inlay_hint_length: Option<usize>,
) -> Option<()> {
    let _p = profile("get_inlay_hints");
    let db = sb.db;
    let analyzer = Lazy::new(move || sb.analyze(hir::InFile::new(file_id.into(), node), None));
    match_ast! {
        match node {
            ast::CallExpr(it) => {
                get_param_name_hints(acc, db, &analyzer, ast::Expr::from(it));
            },
            ast::MethodCallExpr(it) => {
                get_param_name_hints(acc, db, &analyzer, ast::Expr::from(it));
            },
            ast::BindPat(it) => {
                if should_not_display_type_hint(&it) {
                    return None;
                }
                let pat = ast::Pat::from(it);
                let ty = analyzer.type_of_pat(db, &pat)?;
                if ty.is_unknown() {
                    return None;
                }

                acc.push(
                    InlayHint {
                        range: pat.syntax().text_range(),
                        kind: InlayKind::TypeHint,
                        label: ty.display_truncated(db, max_inlay_hint_length).to_string().into(),
                    }
                );
            },
            _ => (),
        }
    };
    Some(())
}

fn should_not_display_type_hint(bind_pat: &ast::BindPat) -> bool {
    for node in bind_pat.syntax().ancestors() {
        match_ast! {
            match node {
                ast::LetStmt(it) => {
                    return it.ascribed_type().is_some()
                },
                ast::Param(it) => {
                    return it.ascribed_type().is_some()
                },
                _ => (),
            }
        }
    }
    false
}

fn get_param_name_hints(
    acc: &mut Vec<InlayHint>,
    db: &RootDatabase,
    analyzer: &SourceAnalyzer,
    expr: ast::Expr,
) -> Option<()> {
    let args = match &expr {
        ast::Expr::CallExpr(expr) => expr.arg_list()?.args(),
        ast::Expr::MethodCallExpr(expr) => expr.arg_list()?.args(),
        _ => return None,
    };

    let mut parameters = get_fn_signature(db, analyzer, &expr)?.parameter_names.into_iter();

    if let ast::Expr::MethodCallExpr(_) = &expr {
        parameters.next();
    };

    let hints = parameters
        .zip(args)
        .filter_map(|(param, arg)| {
            if arg.syntax().kind() == SyntaxKind::LITERAL && !param.is_empty() {
                Some((arg.syntax().text_range(), param))
            } else {
                None
            }
        })
        .map(|(range, param_name)| InlayHint {
            range,
            kind: InlayKind::ParameterHint,
            label: param_name.into(),
        });

    acc.extend(hints);
    Some(())
}

fn get_fn_signature(
    db: &RootDatabase,
    analyzer: &SourceAnalyzer,
    expr: &ast::Expr,
) -> Option<FunctionSignature> {
    match expr {
        ast::Expr::CallExpr(expr) => {
            // FIXME: Type::as_callable is broken for closures
            let callable_def = analyzer.type_of(db, &expr.expr()?)?.as_callable()?;
            match callable_def {
                hir::CallableDef::FunctionId(it) => {
                    let fn_def = it.into();
                    Some(FunctionSignature::from_hir(db, fn_def))
                }
                hir::CallableDef::StructId(it) => FunctionSignature::from_struct(db, it.into()),
                hir::CallableDef::EnumVariantId(it) => {
                    FunctionSignature::from_enum_variant(db, it.into())
                }
            }
        }
        ast::Expr::MethodCallExpr(expr) => {
            let fn_def = analyzer.resolve_method_call(&expr)?;
            Some(FunctionSignature::from_hir(db, fn_def))
        }
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use insta::assert_debug_snapshot;

    use crate::mock_analysis::single_file;

    #[test]
    fn default_generic_types_should_not_be_displayed() {
        let (analysis, file_id) = single_file(
            r#"
struct Test<K, T = u8> {<commit_msg>Show more parameter name hints<commit_after>//! FIXME: write short doc here

use hir::{Function, HirDisplay, SourceAnalyzer, SourceBinder};
use once_cell::unsync::Lazy;
use ra_ide_db::RootDatabase;
use ra_prof::profile;
use ra_syntax::{
    ast::{self, ArgListOwner, AstNode, TypeAscriptionOwner},
    match_ast, SmolStr, SourceFile, SyntaxNode, TextRange,
};

use crate::{FileId, FunctionSignature};

#[derive(Debug, PartialEq, Eq)]
pub enum InlayKind {
    TypeHint,
    ParameterHint,
}

#[derive(Debug)]
pub struct InlayHint {
    pub range: TextRange,
    pub kind: InlayKind,
    pub label: SmolStr,
}

pub(crate) fn inlay_hints(
    db: &RootDatabase,
    file_id: FileId,
    file: &SourceFile,
    max_inlay_hint_length: Option<usize>,
) -> Vec<InlayHint> {
    let mut sb = SourceBinder::new(db);
    let mut res = Vec::new();
    for node in file.syntax().descendants() {
        get_inlay_hints(&mut res, &mut sb, file_id, &node, max_inlay_hint_length);
    }
    res
}

fn get_inlay_hints(
    acc: &mut Vec<InlayHint>,
    sb: &mut SourceBinder<RootDatabase>,
    file_id: FileId,
    node: &SyntaxNode,
    max_inlay_hint_length: Option<usize>,
) -> Option<()> {
    let _p = profile("get_inlay_hints");
    let db = sb.db;
    let analyzer = Lazy::new(move || sb.analyze(hir::InFile::new(file_id.into(), node), None));
    match_ast! {
        match node {
            ast::CallExpr(it) => {
                get_param_name_hints(acc, db, &analyzer, ast::Expr::from(it));
            },
            ast::MethodCallExpr(it) => {
                get_param_name_hints(acc, db, &analyzer, ast::Expr::from(it));
            },
            ast::BindPat(it) => {
                if should_not_display_type_hint(&it) {
                    return None;
                }
                let pat = ast::Pat::from(it);
                let ty = analyzer.type_of_pat(db, &pat)?;
                if ty.is_unknown() {
                    return None;
                }

                acc.push(
                    InlayHint {
                        range: pat.syntax().text_range(),
                        kind: InlayKind::TypeHint,
                        label: ty.display_truncated(db, max_inlay_hint_length).to_string().into(),
                    }
                );
            },
            _ => (),
        }
    };
    Some(())
}

fn should_not_display_type_hint(bind_pat: &ast::BindPat) -> bool {
    for node in bind_pat.syntax().ancestors() {
        match_ast! {
            match node {
                ast::LetStmt(it) => {
                    return it.ascribed_type().is_some()
                },
                ast::Param(it) => {
                    return it.ascribed_type().is_some()
                },
                _ => (),
            }
        }
    }
    false
}

fn get_param_name_hints(
    acc: &mut Vec<InlayHint>,
    db: &RootDatabase,
    analyzer: &SourceAnalyzer,
    expr: ast::Expr,
) -> Option<()> {
    let args = match &expr {
        ast::Expr::CallExpr(expr) => expr.arg_list()?.args(),
        ast::Expr::MethodCallExpr(expr) => expr.arg_list()?.args(),
        _ => return None,
    }
    .into_iter()
    // we need args len to determine whether to skip or not the &self parameter
    .collect::<Vec<_>>();

    let (has_self_param, fn_signature) = get_fn_signature(db, analyzer, &expr)?;
    let parameters = if has_self_param && fn_signature.parameter_names.len() > args.len() {
        fn_signature.parameter_names.into_iter().skip(1)
    } else {
        fn_signature.parameter_names.into_iter().skip(0)
    };

    let hints =
        parameters
            .zip(args)
            .filter_map(|(param, arg)| {
                if !param.is_empty() {
                    Some((arg.syntax().text_range(), param))
                } else {
                    None
                }
            })
            .map(|(range, param_name)| InlayHint {
                range,
                kind: InlayKind::ParameterHint,
                label: param_name.into(),
            });

    acc.extend(hints);
    Some(())
}

fn get_fn_signature(
    db: &RootDatabase,
    analyzer: &SourceAnalyzer,
    expr: &ast::Expr,
) -> Option<(bool, FunctionSignature)> {
    match expr {
        ast::Expr::CallExpr(expr) => {
            // FIXME: Type::as_callable is broken for closures
            let callable_def = analyzer.type_of(db, &expr.expr()?)?.as_callable()?;
            match callable_def {
                hir::CallableDef::FunctionId(it) => {
                    let fn_def: Function = it.into();
                    Some((fn_def.has_self_param(db), FunctionSignature::from_hir(db, fn_def)))
                }
                hir::CallableDef::StructId(it) => FunctionSignature::from_struct(db, it.into())
                    .map(|signature| (false, signature)),
                hir::CallableDef::EnumVariantId(it) => {
                    FunctionSignature::from_enum_variant(db, it.into())
                        .map(|signature| (false, signature))
                }
            }
        }
        ast::Expr::MethodCallExpr(expr) => {
            let fn_def = analyzer.resolve_method_call(&expr)?;
            Some((fn_def.has_self_param(db), FunctionSignature::from_hir(db, fn_def)))
        }
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use insta::assert_debug_snapshot;

    use crate::mock_analysis::single_file;

    #[test]
    fn default_generic_types_should_not_be_displayed() {
        let (analysis, file_id) = single_file(
            r#"
struct Test<K, T = u8> {
{'fraction_non_alphanumeric': 0.13749294184076793, 'fraction_numerical': 0.0003764351590438547, 'mean_word_length': 1.9576955190648484, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 68, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '223865', 'n_tokens_mistral': 3396, 'n_tokens_neox': 3307, 'n_words': 606}