Skip to content
Merged
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
6 changes: 5 additions & 1 deletion src/engine/analyzer/python/common/python-analyzer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -744,7 +744,11 @@ class PythonAnalyzer extends (Analyzer as any) {
} else {
scopeName = `<block_${Uuid.v4()}>`
}
const block_scope = Scope.createSubScope(scopeName, scope, 'scope')
let block_scope = scope
if (node.parent?.type === 'FunctionDefinition') {
// 只对函数体内的块语句创建子作用域,python的其他块语句不创建子作用域
block_scope = Scope.createSubScope(scopeName, scope, 'scope')
}
Comment on lines +747 to +751
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This logic can be made more concise by using a ternary operator. This also allows block_scope to be declared with const, which is generally preferred for variables that are not reassigned.

Suggested change
let block_scope = scope
if (node.parent?.type === 'FunctionDefinition') {
// 只对函数体内的块语句创建子作用域,python的其他块语句不创建子作用域
block_scope = Scope.createSubScope(scopeName, scope, 'scope')
}
// 只对函数体内的块语句创建子作用域,python的其他块语句不创建子作用域
const block_scope =
node.parent?.type === 'FunctionDefinition'
? Scope.createSubScope(scopeName, scope, 'scope')
: scope

Copy link

Choose a reason for hiding this comment

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

List comprehensions may lose scope isolation in Python 3

Medium Severity

The change only creates subscopes for ScopedStatement nodes whose parent is FunctionDefinition. The PR description claims list comprehensions don't define scopes in Python, but this is incorrect for Python 3 where list comprehensions DO have their own scope (the loop variable doesn't leak to the enclosing scope). If the YASA-UAST parser doesn't wrap list comprehensions in FunctionDefinition nodes (as it does for lambdas and class bodies), comprehension variables would incorrectly be analyzed as belonging to the outer scope, potentially causing incorrect analysis results.

Fix in Cursor Fix in Web

node.body
.filter((n: any) => needCompileFirst(n.type))
.forEach((s: any) => this.processInstruction(block_scope, s, state))
Expand Down