use std::collections::{HashMap, HashSet};
use crate::{
BodyId, DefId, ExprId, ImplId, SourceId, Span, Type,
analysis::SymbolOccurrence,
ast::{Expr, Program, Stmt},
types::FunctionSignature,
};
mod callable_lookup;
mod capabilities;
pub use capabilities::{
CallableCapabilities, CallableKind, callable_contract_signature, infer_callable_generics,
};
mod calls;
mod patterns;
pub(crate) use calls::{resolve_program_calls, resolve_project_calls};
pub use patterns::{MatchPattern, ResolvedPattern, VariantId};
mod declaration_types;
use callable_lookup::*;
pub(crate) use declaration_types::associated_signature_bindings;
mod documents;
mod expression_ids;
mod function_references;
pub(crate) use function_references::FunctionReferences;
pub(crate) use function_references::callee_span;
use function_references::{callee_definition, lexical_callee_definition};
mod syntax_ids;
mod visit;
pub use declaration_types::{
DeclarationTypeResolver, SourceMethodId, TraitObligation, requires_storage_declaration,
source_type_path,
};
pub use expression_ids::ExpressionIdentityMap;
pub(crate) use expression_ids::{ExpressionIds, ExpressionTypes};
pub use syntax_ids::{PatternIdentityMap, TypeIdentityMap};
use visit::visit_statements;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SymbolKind {
Variable,
Parameter,
Function,
Macro,
Type,
Trait,
Method,
Field,
Variant,
Module,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SymbolContainer {
Module(String),
Type(String),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DefinitionData {
pub id: DefId,
pub name: String,
pub span: Span,
pub kind: SymbolKind,
pub container: Option<SymbolContainer>,
pub inferred_type: Option<Type>,
pub detail: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DefMap {
definitions: HashMap<DefId, DefinitionData>,
resolutions: HashMap<Span, DefId>,
external_functions: HashMap<Span, crate::analysis::ExternalFunction>,
bodies: HashMap<Span, BodyId>,
definition_bodies: HashMap<DefId, BodyId>,
impls: HashMap<Span, ImplId>,
}
impl DefMap {
pub(crate) fn from_symbols_and_owners(
symbols: &[SymbolOccurrence],
owners: SemanticOwnerIds,
) -> Self {
let mut result = Self::default();
for symbol in SymbolOccurrence::source_last(symbols) {
if let Some(identity) = &symbol.external_function {
result
.external_functions
.insert(symbol.span, identity.clone());
}
let id = if symbol.is_definition {
let Some(id) = symbol.symbol_id else {
continue;
};
result.definitions.insert(
id,
DefinitionData {
id,
name: symbol.name.clone(),
span: symbol.span,
kind: symbol.kind,
container: symbol.container.clone(),
inferred_type: symbol.inferred_type.clone(),
detail: symbol.detail.clone(),
},
);
id
} else {
let Some(id) = symbol.definition_id else {
continue;
};
id
};
result
.resolutions
.insert(symbol.span, symbol.definition_id.unwrap_or(id));
}
for (definition, body_span) in owners.bodies {
let body = BodyId(definition);
result.bodies.insert(body_span, body);
result.definition_bodies.insert(definition, body);
}
for (span, id) in owners.impls {
result.impls.insert(span, id);
}
result
}
pub fn definition(&self, id: DefId) -> Option<&DefinitionData> {
self.definitions.get(&id)
}
pub fn resolution(&self, span: Span) -> Option<DefId> {
self.resolutions.get(&span).copied()
}
pub fn external_function(&self, span: Span) -> Option<&crate::analysis::ExternalFunction> {
self.external_functions.get(&span)
}
pub fn definition_at(&self, span: Span) -> Option<&DefinitionData> {
self.resolution(span).and_then(|id| self.definition(id))
}
pub fn definitions(&self) -> impl Iterator<Item = &DefinitionData> {
self.definitions.values()
}
pub fn body(&self, definition: DefId) -> Option<BodyId> {
self.definition_bodies.get(&definition).copied()
}
pub fn body_at(&self, span: Span) -> Option<BodyId> {
self.bodies.get(&span).copied()
}
pub fn impl_at(&self, span: Span) -> Option<ImplId> {
self.impls.get(&span).copied()
}
pub fn impls(&self) -> impl Iterator<Item = (Span, ImplId)> + '_ {
self.impls.iter().map(|(span, id)| (*span, *id))
}
pub(crate) fn extend(&mut self, other: Self) {
self.definitions.extend(other.definitions);
self.resolutions.extend(other.resolutions);
self.external_functions.extend(other.external_functions);
self.bodies.extend(other.bodies);
self.definition_bodies.extend(other.definition_bodies);
self.impls.extend(other.impls);
}
}
#[derive(Default)]
pub(crate) struct SemanticOwnerIds {
bodies: Vec<(DefId, Span)>,
impls: Vec<(Span, ImplId)>,
next_impl_by_source: HashMap<SourceId, u32>,
}
impl SemanticOwnerIds {
pub(crate) fn record_body(&mut self, definition: DefId, span: Span) {
self.bodies.push((definition, span));
}
pub(crate) fn allocate_impl(&mut self, span: Span, fallback_source: SourceId) -> ImplId {
let source = if span.source == SourceId::UNKNOWN {
fallback_source
} else {
span.source
};
let next = self.next_impl_by_source.entry(source).or_insert(0);
assert!(
*next < crate::database::identities::PERSISTENT_ID_BIT,
"impl id overflow"
);
let id = ImplId {
source,
local: *next,
};
*next = next.checked_add(1).expect("impl id overflow");
self.impls.push((span, id));
id
}
pub(crate) fn record_impl(&mut self, span: Span, id: ImplId) {
self.impls.push((span, id));
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ResolvedCall {
Definition(DefId),
SumConstructor {
name: &'static str,
},
BuiltinImpl {
implementation: String,
method: String,
receiver: rils_builtins::ReceiverMode,
target: Type,
},
TraitDefault {
trait_name: &'static str,
method: &'static str,
receiver: rils_builtins::ReceiverMode,
},
Native {
symbol: &'static str,
receiver: Option<rils_builtins::ReceiverMode>,
},
NumericIntrinsic {
symbol: &'static str,
receiver: Option<rils_builtins::ReceiverMode>,
},
Host {
path: String,
},
Import {
name: String,
signature: FunctionSignature,
capability: String,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NominalOwner {
Source {
name: std::sync::Arc<str>,
declaration: Span,
},
Builtin(&'static str),
Host(std::sync::Arc<str>),
}
pub use NominalOwner as RecordOwner;
impl NominalOwner {
pub fn name(&self) -> &str {
match self {
Self::Source { name, .. } | Self::Host(name) => name,
Self::Builtin(name) => name,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedField {
pub owner: NominalOwner,
pub index: usize,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TypeckResults {
pub(crate) resolved_patterns: HashMap<ExprId, std::sync::Arc<crate::ast::Pattern>>,
executable_patterns: HashMap<ExprId, std::sync::Arc<ResolvedPattern>>,
pub callable_capabilities: CallableCapabilities,
pub(crate) function_signatures: HashMap<Span, Type>,
expression_ids: ExpressionIds,
expression_types: HashMap<ExprId, Type>,
resolved_calls: HashMap<ExprId, ResolvedCall>,
resolved_values: HashMap<ExprId, DefId>,
resolved_fields: HashMap<ExprId, ResolvedField>,
}
impl TypeckResults {
pub(crate) fn set_expression_types(
&mut self,
expression_ids: ExpressionIds,
expression_types: HashMap<ExprId, Type>,
) {
self.expression_ids = expression_ids;
self.expression_types = expression_types;
}
pub fn expression_ids_at(&self, span: Span) -> &[ExprId] {
self.expression_ids.at(span)
}
pub fn expression_span(&self, id: ExprId) -> Option<Span> {
self.expression_ids.span(id)
}
pub fn expression_type(&self, id: ExprId) -> Option<&Type> {
self.expression_types.get(&id)
}
pub fn arm_pattern<'a>(
&'a self,
identities: &ExpressionIdentityMap,
arm: &'a crate::ast::MatchArm,
) -> &'a crate::ast::Pattern {
if self.resolved_patterns.is_empty() {
return &arm.pattern;
}
identities
.get(&arm.expression)
.and_then(|id| self.resolved_patterns.get(&id))
.map_or(&arm.pattern, std::sync::Arc::as_ref)
}
pub fn executable_pattern(&self, arm: ExprId) -> Option<&ResolvedPattern> {
self.executable_patterns.get(&arm).map(AsRef::as_ref)
}
pub fn function_signature(&self, body: Span) -> Option<&Type> {
self.function_signatures.get(&body)
}
pub fn expression_type_ending_at(
&self,
source: SourceId,
end: usize,
) -> Option<(ExprId, &Type)> {
self.expression_types
.iter()
.filter_map(|(id, ty)| Some((*id, self.expression_span(*id)?, ty)))
.filter(|(_, span, _)| span.source == source && span.end == end)
.max_by_key(|(_, span, _)| span.start)
.map(|(id, _, ty)| (id, ty))
}
pub fn resolved_call(&self, id: ExprId) -> Option<&ResolvedCall> {
self.resolved_calls.get(&id)
}
pub fn has_trait_default_calls(&self) -> bool {
self.resolved_calls
.values()
.any(|call| matches!(call, ResolvedCall::TraitDefault { .. }))
}
pub fn has_builtin_impl_calls(&self) -> bool {
self.resolved_calls
.values()
.any(|call| matches!(call, ResolvedCall::BuiltinImpl { .. }))
}
pub fn resolved_value(&self, id: ExprId) -> Option<DefId> {
self.resolved_values.get(&id).copied()
}
pub fn resolved_field(&self, id: ExprId) -> Option<&ResolvedField> {
self.resolved_fields.get(&id)
}
pub fn resolved_call_containing(
&self,
source: SourceId,
offset: usize,
) -> Option<(ExprId, &ResolvedCall)> {
self.resolved_calls
.iter()
.filter_map(|(id, call)| Some((*id, self.expression_span(*id)?, call)))
.filter(|(_, span, _)| {
span.source == source && span.start <= offset && offset <= span.end
})
.min_by_key(|(_, span, _)| span.end.saturating_sub(span.start))
.map(|(id, _, call)| (id, call))
}
pub(crate) fn extend(&mut self, other: Self) {
self.callable_capabilities
.extend(other.callable_capabilities);
self.function_signatures.extend(other.function_signatures);
self.resolved_patterns.extend(other.resolved_patterns);
self.executable_patterns.extend(other.executable_patterns);
self.expression_ids.extend(other.expression_ids);
self.expression_types.extend(other.expression_types);
self.resolved_calls.extend(other.resolved_calls);
self.resolved_values.extend(other.resolved_values);
self.resolved_fields.extend(other.resolved_fields);
}
pub(crate) fn resolve_call(&mut self, id: ExprId, call: ResolvedCall) {
self.resolved_calls.insert(id, call);
}
fn resolve_value(&mut self, id: ExprId, definition: DefId) {
self.resolved_values.insert(id, definition);
}
}
fn qualified_name(namespace: &[String], name: &str) -> String {
if namespace.is_empty() || name.contains("::") {
name.to_owned()
} else {
format!("{}::{name}", namespace.join("::"))
}
}
fn contextual_name(namespace: &[String], self_type: Option<&str>, name: &str) -> String {
if name == "Self" {
return self_type.unwrap_or(name).to_owned();
}
if let Some(suffix) = name.strip_prefix("Self::") {
return self_type
.map(|self_type| format!("{self_type}::{suffix}"))
.unwrap_or_else(|| name.to_owned());
}
if let Some(name) = name.strip_prefix("crate::") {
return name.to_owned();
}
if let Some(name) = name.strip_prefix("self::") {
return qualified_name(namespace, name);
}
if name.starts_with("super::") {
let mut parent = namespace.to_vec();
let mut remainder = name;
while let Some(stripped) = remainder.strip_prefix("super::") {
parent.pop();
remainder = stripped;
}
return qualified_name(&parent, remainder);
}
qualified_name(namespace, name)
}
fn member_span(span: Span, name: &str) -> Span {
Span::in_source(span.source, span.end.saturating_sub(name.len()), span.end)
}
#[cfg(test)]
#[path = "../tests/unit/semantic.rs"]
mod tests;