Skip to content

Commit

Permalink
Hotfix for python imports
Browse files Browse the repository at this point in the history
Should make it better, but still not perfect probably.
  • Loading branch information
oxisto committed Dec 9, 2024
1 parent db340a1 commit 88feea3
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,7 @@ class ExpressionHandler(frontend: PythonLanguageFrontend) :
var ref =
if (isImport(base.name)) {
// Yes, it's an import, so we need to construct a reference with an FQN
newReference(base.name.fqn(node.attr), rawNode = node)
newReference(base.reconstructedImportName.fqn(node.attr), rawNode = node)
} else {
newMemberExpression(name = node.attr, base = base, rawNode = node)
}
Expand Down Expand Up @@ -596,3 +596,17 @@ class ExpressionHandler(frontend: PythonLanguageFrontend) :
return lambda
}
}

/**
* This utility function tries to reconstruct the name as if the expression was part of an imported
* symbol. This is needed because the [MemberExpression.name] includes the [MemberExpression.base]'s
* type instead of the name, and thus it might be "UNKNOWN".
*/
val Expression.reconstructedImportName: Name
get() {
return if (this is MemberExpression) {
this.base.reconstructedImportName.fqn(this.name.localName)
} else {
this.name
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1590,6 +1590,27 @@ class PythonFrontendTest : BaseTest() {
}
}

@Test
fun testImportTest() {
val topLevel = Path.of("src", "test", "resources", "python")
val tu =
analyzeAndGetFirstTU(
listOf(topLevel.resolve("import_test.py").toFile()),
topLevel,
true
) {
it.registerLanguage<PythonLanguage>()
}
assertNotNull(tu)

val refs = tu.refs
refs.forEach { assertIsNot<MemberExpression>(it) }
assertEquals(
setOf("a", "b", "pkg.module.foo", "another_module.foo"),
refs.map { it.name.toString() }.toSet()
)
}

class PythonValueEvaluator : ValueEvaluator() {
override fun computeBinaryOpEffect(
lhsValue: Any?,
Expand Down
5 changes: 5 additions & 0 deletions cpg-language-python/src/test/resources/python/import_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import pkg.module
from pkg import another_module

a = pkg.module.foo
b = another_module.foo

0 comments on commit 88feea3

Please sign in to comment.