From 262053f85c6f1ff01dfac06331aac6fbd0d1a8f2 Mon Sep 17 00:00:00 2001 From: Micha Reiser Date: Thu, 4 Jul 2024 09:17:10 +0200 Subject: [PATCH] [red-knot]: Implement `HasTy` for `Alias` (#11971) --- .../src/semantic_model.rs | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/crates/red_knot_python_semantic/src/semantic_model.rs b/crates/red_knot_python_semantic/src/semantic_model.rs index 5078a44d64..2348ac7150 100644 --- a/crates/red_knot_python_semantic/src/semantic_model.rs +++ b/crates/red_knot_python_semantic/src/semantic_model.rs @@ -163,6 +163,18 @@ impl HasTy for StmtClassDef { } } +impl HasTy for ast::Alias { + fn ty<'db>(&self, model: &SemanticModel<'db>) -> Type<'db> { + let index = semantic_index(model.db, model.file); + let definition = index.definition(self); + + let scope = definition.scope(model.db).to_scope_id(model.db, model.file); + let types = infer_types(model.db, scope); + + types.definition_ty(definition) + } +} + #[cfg(test)] mod tests { use red_knot_module_resolver::{set_module_resolution_settings, ModuleResolutionSettings}; @@ -226,4 +238,26 @@ mod tests { Ok(()) } + + #[test] + fn alias_ty() -> anyhow::Result<()> { + let db = setup_db(); + + db.memory_file_system().write_files([ + ("/src/foo.py", "class Test: pass"), + ("/src/bar.py", "from foo import Test"), + ])?; + let bar = system_path_to_file(&db, "/src/bar.py").unwrap(); + + let ast = parsed_module(&db, bar); + + let import = ast.suite()[0].as_import_from_stmt().unwrap(); + let alias = &import.names[0]; + let model = SemanticModel::new(&db, bar); + let ty = alias.ty(&model); + + assert!(matches!(ty, Type::Class(_))); + + Ok(()) + } }