rils_frontend 0.4.0

Static analysis and semantic frontend for the Rils scripting language
Documentation
//! Keep the source method token linked to the expressions used to select its impl.
use super::*;
use crate::{
    ExprId,
    semantic::{DeclarationTypeResolver, ResolvedCall},
};

pub(crate) enum MethodDispatch<'a> {
    Dot(Option<&'a ResolvedCall>),
    Qualified(&'a Type),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MethodHover {
    pub owner: String,
    pub detail: String,
    pub documentation: &'static str,
}

/// Editor queries at this method token share one declaration selection. The
/// signature lists only arguments written by the caller.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SelectedMethod {
    pub self_type: Option<Type>,
    pub trait_type: Option<Type>,
    pub hover: MethodHover,
    pub definition: Option<Span>,
    pub signature: FunctionSignature,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct MethodSite {
    call: Option<ExprId>,
    callee: Option<ExprId>,
    required: Option<Type>,
    explicit_self: Option<Type>,
    receiver: Option<ExprId>,
    arguments: Vec<ExprId>,
}

impl Analyzer {
    pub(super) fn record_trait_path(
        &mut self,
        span: Span,
        required: Type,
        target: Option<&Type>,
        member: &str,
    ) -> Option<(SymbolKind, Option<Span>)> {
        let mut required = self.declaration_types.resolve(&required, &self.module_path);
        let symbol = if let Some(symbol) = self
            .declaration_types
            .trait_member_symbol(&required, member)
        {
            symbol
        } else {
            let Type::Named { name, .. } = &required else {
                return None;
            };
            self.declaration_types.trait_parameters(name)?;
            let self_type = Type::Variable("Self".into());
            let candidates = self.declaration_types.bound_member_candidates(
                std::slice::from_ref(&required),
                target.unwrap_or(&self_type),
                member,
            );
            if let [(owner, _)] = candidates.as_slice() {
                required = owner.clone();
                self.declaration_types
                    .trait_member_symbol(&required, member)?
            } else {
                let message = if candidates.is_empty() {
                    format!("cannot resolve member `{member}` on trait `{required}`")
                } else {
                    format!("member `{member}` is ambiguous on trait `{required}`")
                };
                let error = AnalysisDiagnostic::error(message, member_name_span(span, member));
                self.result.checked_type_diagnostics.push(error.clone());
                self.result.diagnostics.push(error);
                return Some((SymbolKind::Method, None));
            }
        };
        if symbol.0 == SymbolKind::Method && !self.inside_derive && !span.source.is_generated() {
            self.result.method_sites.insert(
                member_name_span(span, member),
                MethodSite {
                    call: None,
                    callee: None,
                    required: Some(required),
                    explicit_self: target
                        .map(|ty| self.declaration_types.resolve(ty, &self.module_path)),
                    receiver: None,
                    arguments: Vec::new(),
                },
            );
        }
        Some(symbol)
    }

    pub(super) fn record_method_call(&mut self, call: &Expr, callee: &Expr, arguments: &[Expr]) {
        if self.inside_derive || callee.span().source.is_generated() {
            return;
        }
        if let Expr::Member { object, name, span } = callee {
            self.result.method_sites.insert(
                member_name_span(*span, name),
                MethodSite {
                    call: self.expression_ids.get(call),
                    callee: self.expression_ids.get(callee),
                    required: None,
                    explicit_self: None,
                    receiver: self.expression_ids.get(object),
                    arguments: arguments
                        .iter()
                        .map(|arg| self.expression_ids.id(arg))
                        .collect(),
                },
            );
            return;
        }
        let member = match callee {
            Expr::Path { segments, .. } | Expr::GenericPath { segments, .. } => segments.last(),
            Expr::QualifiedPath { member, .. } => Some(member),
            _ => None,
        };
        if let Some(member) = member
            && let Some(site) = self
                .result
                .method_sites
                .get_mut(&member_name_span(callee.span(), member))
        {
            site.call = self.expression_ids.get(call);
            site.callee = self.expression_ids.get(callee);
            let arguments = if site
                .required
                .as_ref()
                .and_then(|ty| self.declaration_types.trait_receiver_mode(ty, member))
                .is_some()
                && let Some((receiver, rest)) = arguments.split_first()
            {
                site.receiver = self.expression_ids.get(receiver);
                rest
            } else {
                arguments
            };
            site.arguments = arguments
                .iter()
                .map(|arg| self.expression_ids.id(arg))
                .collect();
        }
    }
}

impl DocumentAnalysis {
    /// Materialize method selections only when projecting analysis into an editor document.
    pub fn prepare_method_hovers(&mut self, declarations: &DeclarationTypeResolver) {
        let sites = std::mem::take(&mut self.method_sites);
        for symbol in &mut self.symbols {
            if symbol.is_derive_generated || symbol.is_definition {
                continue;
            }
            let Some(site) = sites.get(&symbol.span) else {
                continue;
            };
            let required = site.required.as_ref();
            let receiver = site
                .receiver
                .and_then(|id| self.typeck_results.expression_type(id));
            let target = if let Some(ty) = &site.explicit_self {
                Some(ty)
            } else if let Some(required) = required {
                receiver.and_then(|ty| declarations.trait_call_self(required, &symbol.name, ty))
            } else {
                receiver.map(|ty| declarations.member_target(ty, &symbol.name))
            };
            let arguments: Vec<_> = site
                .arguments
                .iter()
                .map(|id| {
                    self.typeck_results
                        .expression_type(*id)
                        .cloned()
                        .unwrap_or(Type::Unknown)
                })
                .collect();
            let bounds = site
                .receiver
                .and_then(|id| self.bound_trait_members.get(&id));
            let Some(selection) = declarations.select_method_at_call(
                target,
                match required {
                    Some(required) => MethodDispatch::Qualified(required),
                    None => MethodDispatch::Dot(
                        site.call
                            .and_then(|id| self.typeck_results.resolved_call(id)),
                    ),
                },
                &symbol.name,
                &arguments,
                site.call
                    .and_then(|id| self.typeck_results.expression_type(id)),
                bounds.map(Vec::as_slice).unwrap_or_default(),
            ) else {
                if symbol.kind == SymbolKind::Method && symbol.inferred_type.is_none() {
                    symbol.inferred_type = site
                        .callee
                        .and_then(|id| self.typeck_results.expression_type(id))
                        .filter(|ty| matches!(ty, Type::Function { .. }) && ty.is_type_witness())
                        .cloned();
                }
                continue;
            };
            symbol.kind = SymbolKind::Method;
            if symbol.definition_span != selection.definition {
                symbol.definition_span = selection.definition;
                symbol.definition_id = selection
                    .definition
                    .and_then(|span| self.def_map.resolution(span));
            }
            self.selected_methods.insert(symbol.span, selection);
        }
        for symbol in &self.symbols {
            if symbol.kind == SymbolKind::Method
                && !symbol.is_definition
                && !symbol.is_derive_generated
                && symbol.definition_span.is_none()
                && symbol.detail.is_none()
                && symbol.inferred_type.is_none()
                && !self.selected_methods.contains_key(&symbol.span)
                && self.error_covering(symbol.span).is_none()
            {
                self.diagnostics.push(AnalysisDiagnostic::error(
                    format!("cannot resolve the declaration of method `{}`", symbol.name),
                    symbol.span,
                ));
            }
        }
    }

    pub fn error_covering(&self, span: Span) -> Option<&AnalysisDiagnostic> {
        self.diagnostics
            .iter()
            .filter(|error| {
                error.severity == DiagnosticSeverity::Error
                    && error.span.source == span.source
                    && error.span.start <= span.start
                    && error.span.end >= span.end
            })
            .min_by_key(|error| error.span.end - error.span.start)
    }

    pub fn method_hover(&self, span: Span) -> Option<&MethodHover> {
        self.selected_method(span).map(|selection| &selection.hover)
    }

    pub fn selected_method(&self, span: Span) -> Option<&SelectedMethod> {
        self.selected_methods.get(&span)
    }
}