rils_frontend 0.4.0

Static analysis and semantic frontend for the Rils scripting language
Documentation
use super::*;

impl Analyzer {
    pub(super) fn collect_struct_fields(&mut self, statements: &[Stmt]) {
        fn visit(
            statements: &[Stmt],
            prefix: &mut Vec<String>,
            output: &mut HashMap<String, Vec<HashMap<String, StructFieldSymbol>>>,
        ) {
            for statement in statements {
                match statement {
                    Stmt::Struct { name, fields, .. } => {
                        output
                            .entry(crate::semantic::source_type_path(prefix, name))
                            .or_default()
                            .push(
                                fields
                                    .iter()
                                    .map(|field| {
                                        (
                                            field.name.clone(),
                                            StructFieldSymbol {
                                                visibility: Some(field.visibility.clone()),
                                                span: field.span,
                                                ty: field.type_annotation.clone(),
                                                owner: name.clone(),
                                            },
                                        )
                                    })
                                    .collect(),
                            );
                    }
                    Stmt::Module {
                        name,
                        statements: Some(children),
                        ..
                    } => {
                        prefix.push(name.clone());
                        visit(children, prefix, output);
                        prefix.pop();
                    }
                    _ => {}
                }
            }
        }

        visit(
            statements,
            &mut self.module_path.clone(),
            &mut self.struct_fields,
        );
    }

    pub(super) fn enrich_member_symbols(
        &mut self,
        expression_types: &HashMap<crate::ExprId, Type>,
    ) {
        let mut updates = Vec::new();
        for (index, symbol) in self.result.symbols.iter().enumerate() {
            if symbol.is_definition {
                continue;
            }
            let Some(receiver) = self.member_receivers.get(&symbol.span) else {
                continue;
            };
            let Some(receiver_type) = expression_types.get(receiver) else {
                continue;
            };
            let fields = self.result.declared_fields(receiver_type);
            let receiver_type = match receiver_type {
                Type::Reference { inner, .. } => inner.as_ref(),
                receiver_type => receiver_type,
            };
            if let Some(span) = self
                .declaration_types
                .source_method_span(receiver_type, &symbol.name)
                && let Some(method) = self
                    .inherent_methods
                    .get(&symbol.name)
                    .and_then(|methods| methods.iter().find(|method| method.span == span))
                    .cloned()
            {
                let definition_id = self
                    .result
                    .symbols
                    .iter()
                    .find(|candidate| {
                        candidate.is_definition
                            && candidate.kind == SymbolKind::Method
                            && candidate.span == method.span
                    })
                    .and_then(|candidate| candidate.symbol_id);
                updates.push((
                    index,
                    Some(method.span),
                    definition_id,
                    None,
                    Some(method.detail),
                    Some(SymbolContainer::Type(method.owner)),
                    Some(SymbolKind::Method),
                ));
                continue;
            }
            if symbol.kind == SymbolKind::Method
                && !matches!(receiver_type, Type::Named { name, .. } if self.declaration_types.is_declared_type(name))
                && let Some(method) =
                    NativeMethod::on_type(receiver_type, &symbol.name).or_else(|| {
                        let candidates = crate::standard_library::native_trait_method_candidates(
                            &symbol.name,
                            |owner| {
                                self.declaration_types
                                    .implements_trait(receiver_type, owner)
                            },
                        );
                        let [(owner, member)] = candidates.as_slice() else {
                            return None;
                        };
                        let ty = crate::standard_library::builtin_trait_member_type(
                            owner,
                            receiver_type,
                            &symbol.name,
                        )?;
                        NativeMethod::member(member, ty)
                    })
            {
                let detail = self.declaration_types.display_text(&method.detail());
                updates.push((index, None, None, Some(method.ty), Some(detail), None, None));
                continue;
            }
            let field_type = fields
                .iter()
                .find(|(name, _)| name == &symbol.name)
                .map(|(_, ty)| ty);
            let positional = matches!(receiver_type, Type::Tuple(_));
            let native = matches!(receiver_type, Type::Named { name, .. } if !self.declaration_types.is_declared_type(name));
            if positional || native {
                if let Some(ty) = field_type {
                    updates.push((
                        index,
                        None,
                        None,
                        Some(ty.clone()),
                        Some(self.declaration_types.display_text(&declared_field_detail(
                            &symbol.name,
                            ty,
                            Some(Visibility::Public),
                        ))),
                        native.then(|| SymbolContainer::Type(receiver_type.to_string())),
                        Some(SymbolKind::Field),
                    ));
                }
                continue;
            }
            let Type::Named { name, .. } = receiver_type else {
                continue;
            };
            let Some(definitions) = self.struct_fields.get(name) else {
                continue;
            };
            let candidates = definitions
                .iter()
                .filter_map(|fields| fields.get(&symbol.name))
                .collect::<Vec<_>>();
            let [field] = candidates.as_slice() else {
                continue;
            };
            let definition_id = self
                .result
                .symbols
                .iter()
                .find(|candidate| {
                    candidate.is_definition
                        && candidate.kind == SymbolKind::Field
                        && candidate.span == field.span
                })
                .and_then(|candidate| candidate.symbol_id);
            let ty = field_type.unwrap_or(&field.ty);
            updates.push((
                index,
                Some(field.span),
                definition_id,
                Some(ty.clone()),
                Some(self.declaration_types.display_text(&declared_field_detail(
                    &symbol.name,
                    ty,
                    field.visibility.clone(),
                ))),
                Some(SymbolContainer::Type(field.owner.clone())),
                Some(SymbolKind::Field),
            ));
        }
        for (index, definition_span, definition_id, inferred_type, detail, container, kind) in
            updates
        {
            let symbol = &mut self.result.symbols[index];
            symbol.definition_span = definition_span;
            symbol.definition_id = definition_id;
            symbol.inferred_type = inferred_type;
            symbol.detail = detail;
            if container.is_some() {
                symbol.container = container;
            }
            if let Some(kind) = kind {
                symbol.kind = kind;
            }
        }
    }

    fn field_definition(&self, type_name: &str, field_name: &str) -> Option<StructFieldSymbol> {
        if let Some(variant) = self.declaration_types.variant(type_name, &self.module_path) {
            let member = variant
                .fields
                .iter()
                .find(|member| member.name == field_name)?;
            return Some(StructFieldSymbol {
                visibility: None,
                span: member.span,
                ty: member.ty.clone(),
                owner: variant.canonical_path.clone(),
            });
        }
        let Type::Named { name, .. } = self
            .declaration_types
            .resolve(&Type::named(type_name), &self.module_path)
        else {
            return None;
        };
        let definitions = self.struct_fields.get(&name)?;
        let candidates = definitions
            .iter()
            .filter_map(|fields| fields.get(field_name))
            .collect::<Vec<_>>();
        let [field] = candidates.as_slice() else {
            return None;
        };
        Some((*field).clone())
    }

    pub(super) fn record_field_symbol(&mut self, type_name: &str, name: &str, span: Span) {
        let definition = self.field_definition(type_name, name);
        let definition_id = definition.as_ref().and_then(|field| {
            self.result
                .symbols
                .iter()
                .find(|candidate| {
                    candidate.is_definition
                        && candidate.kind == SymbolKind::Field
                        && candidate.span == field.span
                })
                .and_then(|candidate| candidate.symbol_id)
        });
        self.result.symbols.push(SymbolOccurrence {
            is_derive_generated: self.inside_derive,
            external_function: None,
            name: name.to_owned(),
            span,
            definition_span: definition.as_ref().map(|field| field.span),
            symbol_id: None,
            definition_id,
            kind: SymbolKind::Field,
            is_definition: false,
            inferred_type: definition.as_ref().map(|field| field.ty.clone()),
            detail: definition.as_ref().map(|definition| {
                declared_field_detail(name, &definition.ty, definition.visibility.clone())
            }),
            container: definition.map(|field| SymbolContainer::Type(field.owner)),
        });
    }

    pub(super) fn collect_type_aliases(&mut self, statements: &[Stmt], module: &mut Vec<String>) {
        for statement in statements {
            match statement {
                Stmt::Module {
                    name,
                    statements: Some(statements),
                    ..
                } => {
                    module.push(name.clone());
                    self.collect_type_aliases(statements, module);
                    module.pop();
                }
                Stmt::TypeAlias {
                    name, name_span, ..
                } => {
                    self.type_aliases
                        .insert(*name_span, crate::semantic::source_type_path(module, name));
                }
                _ => {}
            }
        }
    }

    pub(super) fn collect_inherent_methods(&mut self, statements: &[Stmt]) {
        for statement in statements {
            if let Stmt::Module {
                name,
                statements: Some(statements),
                ..
            } = statement
            {
                self.module_path.push(name.clone());
                self.collect_inherent_methods(statements);
                self.module_path.pop();
                continue;
            }
            let Stmt::Impl {
                trait_name: None,
                target: Type::Named { name: owner, .. },
                methods,
                ..
            } = statement
            else {
                continue;
            };
            for method in methods {
                self.inherent_methods
                    .entry(method.name.clone())
                    .or_default()
                    .push(InherentMethod {
                        owner: match self
                            .declaration_types
                            .resolve(&Type::named(owner), &self.module_path)
                        {
                            Type::Named { name, .. } => name,
                            _ => owner.clone(),
                        },
                        span: method.name_span,
                        detail: impl_method_detail(method),
                    });
            }
        }
    }

    pub(super) fn collect_enum_variants(&mut self, statements: &[Stmt]) {
        fn visit(
            statements: &[Stmt],
            prefix: &mut Vec<String>,
            output: &mut HashMap<(String, String), EnumVariantSymbol>,
        ) {
            for statement in statements {
                if let Stmt::Module {
                    name,
                    statements: Some(statements),
                    ..
                } = statement
                {
                    prefix.push(name.clone());
                    visit(statements, prefix, output);
                    prefix.pop();
                    continue;
                }
                let Stmt::Enum { name, variants, .. } = statement else {
                    continue;
                };
                let owner = crate::semantic::source_type_path(prefix, name);
                for variant in variants {
                    let (variant_name, span) = enum_variant_name_and_span(variant);
                    output.insert(
                        (owner.clone(), variant_name.into()),
                        EnumVariantSymbol {
                            span: Some(span),
                            detail: enum_variant_declaration(name, variant),
                            owner: owner.clone(),
                        },
                    );
                }
            }
        }

        visit(statements, &mut Vec::new(), &mut self.enum_variants);
    }

    pub(super) fn collect_host_enum_variants(&mut self) {
        let Some(host) = self.host_contract.as_ref() else {
            return;
        };
        for declaration in host.types() {
            let Some(definition) = declaration.enum_definition.as_ref() else {
                continue;
            };
            let short_name = declaration
                .name
                .rsplit("::")
                .next()
                .unwrap_or(&declaration.name);
            for variant in definition.variants.keys() {
                self.enum_variants.insert(
                    (declaration.name.clone(), variant.clone()),
                    EnumVariantSymbol {
                        span: None,
                        detail: format!("{short_name}::{variant}"),
                        owner: declaration.name.clone(),
                    },
                );
            }
        }
    }
}