Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions crates/ty_ide/src/completion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5334,6 +5334,43 @@ except Type<CURSOR>:
);
}

// Ref: https://github.com/astral-sh/ty/issues/2401
#[test]
fn no_panic_incomplete_except_handler() {
let builder = completion_test_builder(
"\
try:
print()
except <CURSOR># Trigger completion/hover here
",
);

assert_snapshot!(
builder.skip_keywords().skip_builtins().skip_auto_import().build().snapshot(),
@"<No completions found after filtering out completions>",
);
}

// Ref: https://github.com/astral-sh/ty/issues/2401
#[test]
fn incomplete_except_handler_uses_enclosing_scope() {
completion_test_builder(
"\
def f():
sentinel = 1
try:
print()
except <CURSOR>as err:
pass
",
)
.skip_keywords()
.skip_builtins()
.skip_auto_import()
.build()
.contains("sentinel");
}

// Ref: https://github.com/astral-sh/ty/issues/572
#[test]
fn scope_id_missing_global1() {
Expand Down
22 changes: 12 additions & 10 deletions crates/ty_ide/src/goto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ impl GotoTarget<'_> {
GotoTarget::ImportSymbolAlias { alias, .. }
| GotoTarget::ImportModuleAlias { alias, .. }
| GotoTarget::ImportExportedName { alias, .. } => alias.inferred_type(model),
GotoTarget::ExceptVariable(except) => except.inferred_type(model),
GotoTarget::ExceptVariable(except) => model.except_handler_type(except),
GotoTarget::KeywordArgument { keyword, .. } => keyword.value.inferred_type(model),
// When asking the type of a callable, usually you want the callable itself?
// (i.e. the type of `MyClass` in `MyClass()` is `<class MyClass>` and not `() -> MyClass`)
Expand Down Expand Up @@ -515,11 +515,9 @@ impl GotoTarget<'_> {
)),

// For exception variables, they are their own definitions (like parameters)
GotoTarget::ExceptVariable(except_handler) => {
Some(vec![ResolvedDefinition::Definition(
except_handler.definition(model),
)])
}
GotoTarget::ExceptVariable(except_handler) => model
.except_handler_definition(except_handler)
.map(|definition| vec![ResolvedDefinition::Definition(definition)]),

// Patterns are glorified assignments but we have to look them up by ident
// because they're not expressions
Expand Down Expand Up @@ -949,9 +947,10 @@ impl GotoTarget<'_> {

None
}
Some(AnyNodeRef::ExceptHandlerExceptHandler(handler)) => {
Some(GotoTarget::ExceptVariable(handler))
}
Some(AnyNodeRef::ExceptHandlerExceptHandler(handler)) => handler
.name
.is_some()
.then_some(GotoTarget::ExceptVariable(handler)),
Some(AnyNodeRef::Keyword(keyword)) => {
// Find the containing call expression from the ancestor chain
let call_expression = covering_node
Expand Down Expand Up @@ -1139,7 +1138,10 @@ impl Ranged for GotoTarget<'_> {
} => *component_range,
GotoTarget::StringAnnotationSubexpr { subrange, .. } => *subrange,
GotoTarget::ImportModuleAlias { asname, .. } => asname.range,
GotoTarget::ExceptVariable(except) => except.name.as_ref().unwrap().range,
GotoTarget::ExceptVariable(except) => except
.name
.as_ref()
.map_or(except.range(), |name| name.range),
GotoTarget::KeywordArgument { keyword, .. } => keyword.arg.as_ref().unwrap().range,
GotoTarget::PatternMatchRest(rest) => rest.rest.as_ref().unwrap().range,
GotoTarget::PatternKeywordArgument(keyword) => keyword.attr.range,
Expand Down
14 changes: 14 additions & 0 deletions crates/ty_ide/src/hover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4952,6 +4952,20 @@ def function():
");
}

// Ref: https://github.com/astral-sh/ty/issues/2401
#[test]
fn hover_incomplete_except_handler() {
let test = cursor_test(
"\
try:
print()
except <CURSOR># Trigger completion/hover here
",
);

assert_snapshot!(test.hover(), @"Hover provided no content");
}

impl CursorTest {
fn hover(&self) -> String {
use std::fmt::Write;
Expand Down
39 changes: 32 additions & 7 deletions crates/ty_python_semantic/src/semantic_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,12 +304,15 @@ impl<'db> SemanticModel<'db> {
.scope(self.db)
.file_scope_id(self.db),
),
ast::AnyNodeRef::ExceptHandlerExceptHandler(handler) => Some(
handler
.definition(self)
.scope(self.db)
.file_scope_id(self.db),
),
ast::AnyNodeRef::ExceptHandlerExceptHandler(handler) => self
.except_handler_definition(handler)
.map(|definition| definition.scope(self.db).file_scope_id(self.db))
.or_else(|| {
handler.type_.as_deref().and_then(|handled_exceptions| {
index.try_expression_scope_id(handled_exceptions)
})
Comment on lines +311 to +313

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
handler.type_.as_deref().and_then(|handled_exceptions| {
index.try_expression_scope_id(handled_exceptions)
})
index.try_expression_scoipe_id(handler.type_.as_deref()?)

})
.or(Some(FileScopeId::global())),
ast::AnyNodeRef::TypeParamTypeVar(var) => {
Some(var.definition(self).scope(self.db).file_scope_id(self.db))
}
Expand All @@ -325,6 +328,29 @@ impl<'db> SemanticModel<'db> {
}
}

/// Returns the definition for an exception-handler variable.
///
/// Exception handlers only have a definition when they bind a name (`except E as name:`).
pub fn except_handler_definition(
&self,
handler: &ast::ExceptHandlerExceptHandler,
) -> Option<Definition<'db>> {
handler.name.as_ref()?;
let index = semantic_index(self.db, self.file);
Some(index.expect_single_definition(handler))
}
Comment on lines +331 to +341

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The API doesn't feel well aligned with HasType and HasDefinition. Maybe introduce a MaybeHasDefinition or HasOptionalDefinition trait and implement that instead. I agree, it feels a bit overkill but it's unfortunately the only way to add a method to a foreign type

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


/// Returns the inferred type of an exception-handler variable.
///
/// Exception handlers only bind a variable when they have a name (`except E as name:`).
pub fn except_handler_type(
&self,
handler: &ast::ExceptHandlerExceptHandler,
) -> Option<Type<'db>> {
let definition = self.except_handler_definition(handler)?;
Some(binding_type(self.db, definition))
}

/// Get a "safe" [`ast::AnyNodeRef`] to use for referring to the given (sub-)AST node.
///
/// If we're analyzing a string annotation, it will return the string literal's node.
Expand Down Expand Up @@ -641,7 +667,6 @@ impl_binding_has_ty_def!(ast::StmtFunctionDef);
impl_binding_has_ty_def!(ast::StmtClassDef);
impl_binding_has_ty_def!(ast::Parameter);
impl_binding_has_ty_def!(ast::ParameterWithDefault);
impl_binding_has_ty_def!(ast::ExceptHandlerExceptHandler);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it was necessary to remove both the HasDefinition and HasType implementations for ExceptHandlerExceptHandler. We can still implement HasType manually, since inferred_type already returns an Option.

impl_binding_has_ty_def!(ast::TypeParamTypeVar);

impl HasType for ast::Alias {
Expand Down