Skip to content

Commit

Permalink
Open a block and function scope for python functions (#1731)
Browse files Browse the repository at this point in the history
  • Loading branch information
oxisto authored Sep 26, 2024
1 parent 1fced84 commit 1b91777
Showing 1 changed file with 20 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,12 @@ class StatementHandler(frontend: PythonLanguageFrontend) :
handleArguments(s.args, result, recordDeclaration)

if (s.body.isNotEmpty()) {
result.body = makeBlock(s.body, parentNode = s)
// Make sure we open a new (block) scope for the function body. This is not a 1:1
// mapping to python scopes, since python only has a "function scope", but in the CPG
// the function scope only comprises the function arguments, and we need a block scope
// to
// hold all local variables within the function body.
result.body = makeBlock(s.body, parentNode = s, enterScope = true)
}

frontend.scopeManager.leaveScope(result)
Expand Down Expand Up @@ -603,16 +608,29 @@ class StatementHandler(frontend: PythonLanguageFrontend) :
* This function "wraps" a list of [Python.AST.BaseStmt] nodes into a [Block]. Since the list
* itself does not have a code/location, we need to employ [codeAndLocationFromChildren] on the
* [parentNode].
*
* Optionally, a new scope will be opened when [enterScope] is specified. This should be done
* VERY carefully, as Python has a very limited set of scopes and is most likely only to be used
* by [handleFunctionDef].
*/
private fun makeBlock(
stmts: List<Python.AST.BaseStmt>,
parentNode: Python.AST.WithLocation
parentNode: Python.AST.WithLocation,
enterScope: Boolean = false,
): Block {
val result = newBlock()
if (enterScope) {
frontend.scopeManager.enterScope(result)
}

for (stmt in stmts) {
result.statements += handle(stmt)
}

if (enterScope) {
frontend.scopeManager.leaveScope(result)
}

// Try to retrieve the code and location from the parent node, if it is a base stmt
var baseStmt = parentNode as? Python.AST.BaseStmt
return if (baseStmt != null) {
Expand Down

0 comments on commit 1b91777

Please sign in to comment.