Skip to content

Python: Support type annotations in call graph #19672

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* Type annotations such as `foo : Bar` are now treated by the call graph as an indication that `foo` may be an instance of `Bar`.
11 changes: 11 additions & 0 deletions python/ql/lib/semmle/python/Exprs.qll
Original file line number Diff line number Diff line change
Expand Up @@ -762,6 +762,17 @@ class Annotation extends Expr {
or
this = any(FunctionExpr f).getReturns()
}

/** Gets the expression that this annotation annotates. */
Expr getAnnotatedExpression() {
result = any(AnnAssign a | a.getAnnotation() = this).getTarget()
or
result = any(Parameter p | p.getAnnotation() = this)
or
exists(FunctionExpr f |
this = f.getReturns() and result = f.getInnerScope().getReturnNode().getNode()
)
}
}

/* Expression Contexts */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -580,6 +580,11 @@ private module TrackClassInstanceInput implements CallGraphConstruction::Simple:
class State = Class;

predicate start(Node start, Class cls) {
exists(Annotation ann |
ann = classTracker(cls).asExpr() and
start.asExpr() = ann.getAnnotatedExpression()
)
or
resolveClassCall(start.(CallCfgNode).asCfgNode(), cls)
or
// result of `super().__new__` as used in a `__new__` method implementation
Expand Down