rils_frontend 0.4.0

Static analysis and semantic frontend for the Rils scripting language
Documentation
//! Shared analysis results and diagnostic aggregation.
use std::collections::HashMap;

use crate::{
    source::{Span, SymbolId},
    types::Type,
};

use super::{InlayTypeLink, SymbolContainer, SymbolKind, scope};

/// Source-independent function identity within this analysis's declaration context.
/// Host paths identify an overload set; signature selection happens at the call site.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum ExternalFunction {
    Builtin(String),
    Host(String),
}

/// A module binding retaining its original declaration and access scope.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExternalModuleExport {
    pub canonical_path: String,
    pub visibility: crate::exports::ExportVisibility,
    pub declaration_visibility: crate::exports::ExportVisibility,
    /// Canonical member namespace for module and enum aliases.
    pub target_module: Option<String>,
    pub name: String,
    pub span: Option<Span>,
    pub external_function: Option<ExternalFunction>,
    pub definition_id: Option<SymbolId>,
    pub kind: SymbolKind,
    pub inferred_type: Option<Type>,
    pub detail: Option<String>,
    pub module_path: String,
    pub fields: Vec<ExternalTypeField>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExternalTypeField {
    /// Enum variant fields inherit their variant's visibility.
    pub visibility: Option<crate::ast::Visibility>,
    pub name: String,
    pub span: Span,
    pub ty: Type,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SymbolOccurrence {
    /// Its span is a diagnostic anchor supplied by a derive, not a token in the source.
    pub(crate) is_derive_generated: bool,
    pub name: String,
    pub span: Span,
    pub definition_span: Option<Span>,
    pub symbol_id: Option<SymbolId>,
    pub definition_id: Option<SymbolId>,
    pub external_function: Option<ExternalFunction>,
    pub kind: SymbolKind,
    pub is_definition: bool,
    pub inferred_type: Option<Type>,
    pub detail: Option<String>,
    pub container: Option<SymbolContainer>,
}

impl SymbolOccurrence {
    /// A source token takes precedence over an expansion using it as an anchor
    /// in indexes keyed by span.
    pub(crate) fn source_last(symbols: &[Self]) -> impl Iterator<Item = &Self> {
        symbols
            .iter()
            .filter(|s| s.is_derive_generated)
            .chain(symbols.iter().filter(|s| !s.is_derive_generated))
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AnalysisDiagnostic {
    pub message: String,
    pub span: Span,
    pub severity: DiagnosticSeverity,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DiagnosticSeverity {
    Error,
    Warning,
}

impl AnalysisDiagnostic {
    /// Creates an error diagnostic that can be attached to a best-effort
    /// analysis result by editor tooling.
    pub fn error(message: impl Into<String>, span: Span) -> Self {
        Self {
            message: message.into(),
            span,
            severity: DiagnosticSeverity::Error,
        }
    }

    pub(crate) fn warning(message: impl Into<String>, span: Span) -> Self {
        Self {
            message: message.into(),
            span,
            severity: DiagnosticSeverity::Warning,
        }
    }
}

/// A module import after resolving visibility, aliases and re-exports.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ImportedDeclaration {
    pub name: String,
    pub canonical_path: String,
    pub kind: SymbolKind,
    pub external_function: Option<ExternalFunction>,
}

pub type ModuleImports = HashMap<Span, Vec<ImportedDeclaration>>;

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DocumentAnalysis {
    pub module_imports: ModuleImports,
    /// Revisions supplying persistent declaration IDs; IDs alone are not cache keys.
    pub source_revisions: HashMap<crate::SourceId, u64>,
    pub(super) lexical_scopes: Vec<scope::LexicalScope>,
    pub(super) associated_owners: HashMap<Span, Type>,
    pub(super) method_sites: HashMap<Span, super::method_hover::MethodSite>,
    pub(super) selected_methods: HashMap<Span, super::SelectedMethod>,
    pub(super) native_trait_members: HashMap<Type, Vec<(String, String)>>,
    pub(super) declared_trait_members: HashMap<Type, Vec<(Type, String, Type)>>,
    pub(super) inherent_completions: HashMap<Type, Vec<(String, String)>>,
    pub(super) declared_fields: HashMap<Type, Vec<(String, Type)>>,
    pub(super) bound_trait_members: HashMap<crate::ExprId, Vec<(Type, String, Type)>>,
    pub diagnostics: Vec<AnalysisDiagnostic>,
    /// All ownership errors, including non-generic bodies, for execution prechecks.
    pub ownership_diagnostics: Vec<AnalysisDiagnostic>,
    /// Generic bodies must be valid for their declared bounds, independently of
    /// the concrete arguments a dynamic interpreter happens to receive.
    pub generic_ownership_diagnostics: Vec<AnalysisDiagnostic>,
    pub generic_type_diagnostics: Vec<AnalysisDiagnostic>,
    /// Unresolved value types and control-flow errors that block evaluation of a snippet.
    pub checked_type_diagnostics: Vec<AnalysisDiagnostic>,
    pub pattern_diagnostics: Vec<AnalysisDiagnostic>,
    /// Callable contracts and linear invocation, shared by all execution backends.
    pub callable_diagnostics: Vec<AnalysisDiagnostic>,
    /// Source access restrictions required before evaluating any statements.
    pub visibility_diagnostics: Vec<AnalysisDiagnostic>,
    /// Implementation uniqueness and orphan rules required before dispatch.
    pub impl_coherence_diagnostics: Vec<AnalysisDiagnostic>,
    /// Invalid storage declarations must be rejected even when never constructed.
    pub data_diagnostics: Vec<AnalysisDiagnostic>,
    pub layout_diagnostics: Vec<AnalysisDiagnostic>,
    /// Source-owned projections requiring a concrete generic instantiation.
    pub generic_shared_projections: HashMap<crate::BodyId, Vec<crate::SharedProjectionConstraint>>,
    pub symbols: Vec<SymbolOccurrence>,
    pub inlay_hints: Vec<InlayTypeHint>,
    pub def_map: crate::semantic::DefMap,
    pub typeck_results: crate::semantic::TypeckResults,
    pub host_type_resolutions: crate::HostTypeResolutionResults,
    pub verified_trait_impls: Vec<crate::ImplId>,
    pub(super) verified_trait_impl_spans: Vec<Span>,
}

impl DocumentAnalysis {
    pub(crate) fn sort_diagnostics(&mut self) {
        for diagnostics in [
            &mut self.diagnostics,
            &mut self.ownership_diagnostics,
            &mut self.pattern_diagnostics,
            &mut self.checked_type_diagnostics,
            &mut self.visibility_diagnostics,
            &mut self.impl_coherence_diagnostics,
        ] {
            diagnostics.sort_by_key(|diagnostic| {
                (
                    diagnostic.span.source,
                    diagnostic.span.start,
                    diagnostic.span.end,
                )
            });
            diagnostics
                .dedup_by(|left, right| left.span == right.span && left.message == right.message);
        }
    }

    /// Applicable native trait methods for a resolved receiver type.
    pub fn native_trait_members(&self, receiver: &Type) -> &[(String, String)] {
        self.native_trait_members
            .get(receiver)
            .map_or(&[], Vec::as_slice)
    }
    /// Returns the first blocking diagnostic in source order.
    pub fn first_error(&self) -> Option<&AnalysisDiagnostic> {
        self.diagnostics
            .iter()
            .find(|diagnostic| diagnostic.severity == DiagnosticSeverity::Error)
    }

    pub(crate) fn extend(&mut self, other: Self) {
        self.module_imports.extend(other.module_imports);
        self.associated_owners.extend(other.associated_owners);
        self.method_sites.extend(other.method_sites);
        self.native_trait_members.extend(other.native_trait_members);
        self.declared_trait_members
            .extend(other.declared_trait_members);
        self.bound_trait_members.extend(other.bound_trait_members);
        self.inherent_completions.extend(other.inherent_completions);
        self.declared_fields.extend(other.declared_fields);
        self.lexical_scopes.extend(other.lexical_scopes);
        self.source_revisions.extend(other.source_revisions);
        self.diagnostics.extend(other.diagnostics);
        self.ownership_diagnostics
            .extend(other.ownership_diagnostics);
        self.generic_ownership_diagnostics
            .extend(other.generic_ownership_diagnostics);
        self.generic_type_diagnostics
            .extend(other.generic_type_diagnostics);
        self.callable_diagnostics.extend(other.callable_diagnostics);
        self.visibility_diagnostics
            .extend(other.visibility_diagnostics);
        self.data_diagnostics.extend(other.data_diagnostics);
        self.pattern_diagnostics.extend(other.pattern_diagnostics);
        self.checked_type_diagnostics
            .extend(other.checked_type_diagnostics);
        self.layout_diagnostics.extend(other.layout_diagnostics);
        self.impl_coherence_diagnostics
            .extend(other.impl_coherence_diagnostics);
        for (body, projections) in other.generic_shared_projections {
            self.generic_shared_projections
                .entry(body)
                .or_default()
                .extend(projections);
        }
        self.symbols.extend(other.symbols);
        self.inlay_hints.extend(other.inlay_hints);
        self.def_map.extend(other.def_map);
        self.typeck_results.extend(other.typeck_results);
        self.host_type_resolutions
            .extend(other.host_type_resolutions);
        self.verified_trait_impls.extend(other.verified_trait_impls);
        self.verified_trait_impl_spans
            .extend(other.verified_trait_impl_spans);
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InlayTypeHint {
    pub position: usize,
    pub span: Span,
    pub label: String,
    pub links: Vec<InlayTypeLink>,
}

#[cfg(test)]
#[path = "../../tests/unit/analysis_results.rs"]
mod tests;