Skip to content

Python: Add API graph support for parameter annotations #18112

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

Merged
merged 1 commit into from
Dec 5, 2024
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
category: feature
---

- Added support for parameter annotations in API graphs. This means that in a function definition such as `def foo(x: Bar): ...`, you can now use the `getInstanceFromAnnotation()` method to step from `Bar` to `x`. In addition to this, the `getAnInstance` method now also includes instances arising from parameter annotations.
23 changes: 22 additions & 1 deletion python/ql/lib/semmle/python/ApiGraphs.qll
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,12 @@ module API {
*/
Node getReturn() { result = this.getASuccessor(Label::return()) }

/**
* Gets a node representing instances of the class represented by this node, as specified via
* type annotations.
*/
Node getInstanceFromAnnotation() { result = this.getASuccessor(Label::annotation()) }

/**
* Gets a node representing the `i`th parameter of the function represented by this node.
*
Expand Down Expand Up @@ -229,7 +235,9 @@ module API {
/**
* Gets a node representing an instance of the class (or a transitive subclass of the class) represented by this node.
*/
Node getAnInstance() { result = this.getASubclass*().getReturn() }
Node getAnInstance() {
result in [this.getASubclass*().getReturn(), this.getASubclass*().getInstanceFromAnnotation()]
}

/**
* Gets a node representing the result from awaiting this node.
Expand Down Expand Up @@ -834,6 +842,10 @@ module API {
lbl = Label::return() and
ref = pred.getACall()
or
// Getting an instance via a type annotation
lbl = Label::annotation() and
ref = pred.getAnAnnotatedInstance()
or
// Awaiting a node that is a use of `base`
lbl = Label::await() and
ref = pred.getAnAwaited()
Expand Down Expand Up @@ -1079,6 +1091,7 @@ module API {
} or
MkLabelSelfParameter() or
MkLabelReturn() or
MkLabelAnnotation() or
MkLabelSubclass() or
MkLabelAwait() or
MkLabelSubscript() or
Expand Down Expand Up @@ -1148,6 +1161,11 @@ module API {
override string toString() { result = "getReturn()" }
}

/** A label for annotations. */
class LabelAnnotation extends ApiLabel, MkLabelAnnotation {
override string toString() { result = "getAnnotatedInstance()" }
}

/** A label that gets the subclass of a class. */
class LabelSubclass extends ApiLabel, MkLabelSubclass {
override string toString() { result = "getASubclass()" }
Expand Down Expand Up @@ -1207,6 +1225,9 @@ module API {
/** Gets the `return` edge label. */
LabelReturn return() { any() }

/** Gets the `annotation` edge label. */
LabelAnnotation annotation() { any() }

/** Gets the `subclass` edge label. */
LabelSubclass subclass() { any() }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,11 @@ class LocalSourceNode extends Node {
*/
CallCfgNode getACall() { Cached::call(this, result) }

/**
* Gets a node that has this node as its annotation.
*/
Node getAnAnnotatedInstance() { Cached::annotatedInstance(this, result) }

/**
* Gets an awaited value from this node.
*/
Expand Down Expand Up @@ -275,6 +280,17 @@ private module Cached {
)
}

cached
predicate annotatedInstance(LocalSourceNode node, Node instance) {
exists(ExprNode n | node.flowsTo(n) |
instance.asCfgNode().getNode() =
any(AnnAssign ann | ann.getAnnotation() = n.asExpr()).getTarget()
or
instance.asCfgNode().getNode() =
any(Parameter p | p.getAnnotation() = n.asCfgNode().getNode())
)
}

/**
* Holds if `node` flows to a value that, when awaited, results in `awaited`.
*/
Expand Down
25 changes: 25 additions & 0 deletions python/ql/test/library-tests/ApiGraphs/py3/test_annotations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from types import AssignmentAnnotation, ParameterAnnotation

def test_annotated_assignment():
local_x : AssignmentAnnotation = create_x() #$ MISSING: use=moduleImport("types").getMember("AssignmentAnnotation")
local_x #$ MISSING: use=moduleImport("types").getMember("AssignmentAnnotation").getAnnotatedInstance()

global_x : AssignmentAnnotation #$ use=moduleImport("types").getMember("AssignmentAnnotation")
global_x #$ MISSING: use=moduleImport("types").getMember("AssignmentAnnotation").getAnnotatedInstance()
Copy link
Contributor

Choose a reason for hiding this comment

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

Why is this missing? Is it because there is no assignment on the line above, so that global_x is not in getTarget (which is presumably empty)?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Hmm... This is a very salient question. If I quick-eval the annotatedInstance predicate, I get four results:

  • ControlFlowNode for ImportMember, ControlFlowNode for global_x
  • ControlFlowNode for ImportMember, ControlFlowNode for parameter_y
  • ControlFlowNode for Alias, ControlFlowNode for parameter_z
  • ControlFlowNode for Alias, ControlFlowNode for global_z

So, we are picking up the instancing from from ... import AssignmentAnnotation to global_x : AssignmentAnnotation, but we're not picking up that the annotation is a use of that same identifier as in the import statement. What's curious, then, is that global_x isn't seen as an instance of AssignmentAnnotation. For global_z it makes sense, since we don't understand the simple type aliasing that's taking place on line 13.

Looking at getTarget it does exist for the type ascription of global_x, but it seems that we do not track the flow between the two occurrences of global_x. I'm trying to figure out why now.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

A thought occurred to me after writing that message. Could it be that we're observing that global_x gets overwritten here (because it's the target of an assignment), but then when we go to see what value was assigned we don't find it (because it's just a type ascription)? That would explain the weird behaviour.

Copy link
Contributor

Choose a reason for hiding this comment

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

Yes that could be it. I wonder if global_x in global_x : AssignmentAnnotation should actually be considered a use rather than a def..


def test_parameter_annotation(parameter_y: ParameterAnnotation): #$ use=moduleImport("types").getMember("ParameterAnnotation")
parameter_y #$ use=moduleImport("types").getMember("ParameterAnnotation").getAnnotatedInstance()

type Alias = AssignmentAnnotation

global_z : Alias #$ MISSING: use=moduleImport("types").getMember("AssignmentAnnotation")
global_z #$ MISSING: use=moduleImport("types").getMember("AssignmentAnnotation").getAnnotatedInstance()

def test_parameter_alias(parameter_z: Alias): #$ MISSING: use=moduleImport("types").getMember("AssignmentAnnotation")
parameter_z #$ MISSING: use=moduleImport("types").getMember("AssignmentAnnotation").getAnnotatedInstance()

# local type aliases
def test_local_type_alias():
type LocalAlias = AssignmentAnnotation
local_alias : LocalAlias = create_value() #$ MISSING: use=moduleImport("types").getMember("AssignmentAnnotation")
local_alias #$ MISSING: use=moduleImport("types").getMember("AssignmentAnnotation").getAnnotatedInstance()