Skip to content

Rust: Improve handling of where clauses in type inference and path resolution #20140

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
31 changes: 31 additions & 0 deletions rust/ql/lib/codeql/rust/elements/internal/TraitImpl.qll
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,36 @@ module Impl {
not this.hasGenericParamList() and
result = 0
}

private int nrOfDirectTypeBounds() {
result = this.getTypeBoundList().getNumberOfBounds()
or
not this.hasTypeBoundList() and
result = 0
}

/**
* Gets the `index`th type bound of this trait, if any.
*
* This includes type bounds directly on the trait and bounds from any
* `where` clauses for `Self`.
*/
TypeBound getTypeBound(int index) {
result = this.getTypeBoundList().getBound(index)
or
exists(WherePred wp |
wp = this.getWhereClause().getAPredicate() and
wp.getTypeRepr().(PathTypeRepr).getPath().getText() = "Self" and
Copy link
Preview

Copilot AI Aug 4, 2025

Choose a reason for hiding this comment

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

[nitpick] The hardcoded string comparison getText() = \"Self\" is fragile and may not handle all valid representations of Self. Consider using a more robust method to identify Self type references, such as checking the resolved type or using semantic analysis rather than text comparison.

Suggested change
wp.getTypeRepr().(PathTypeRepr).getPath().getText() = "Self" and
wp.getTypeRepr() instanceof SelfTypeRepr and

Copilot uses AI. Check for mistakes.

result = wp.getTypeBoundList().getBound(index - this.nrOfDirectTypeBounds())
Copy link
Contributor

Choose a reason for hiding this comment

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

It appears to be legal to have two where predicates with Self as the path, e.g.:

    trait Subtrait
    where
        Self: Supertrait1,
        Self: Supertrait2,

I think at the moment this will break your index numbering.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

You're right, that is legal and the implementation currently does not account for that.

Copy link
Contributor

Choose a reason for hiding this comment

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

Did this one get fixed? If not can you write it up as an issue and lets get this PR merged!

)
}

/**
* Gets a type bound of this trait.
*
* This includes type bounds directly on the trait and bounds from any
* `where` clauses for `Self`.
*/
TypeBound getATypeBound() { result = this.getTypeBound(_) }
}
}
36 changes: 36 additions & 0 deletions rust/ql/lib/codeql/rust/elements/internal/TypeParamImpl.qll
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ private import codeql.rust.elements.internal.generated.TypeParam
*/
module Impl {
private import rust
private import codeql.rust.internal.PathResolution

// the following QLdoc is generated: if you need to edit it, do it in the schema file
/**
Expand All @@ -27,6 +28,41 @@ module Impl {
/** Gets the position of this type parameter. */
int getPosition() { this = any(GenericParamList l).getTypeParam(result) }

private TypeBound getTypeBoundAt(int i, int j) {
exists(TypeBoundList tbl | result = tbl.getBound(j) |
tbl = this.getTypeBoundList() and i = 0
or
exists(WherePred wp |
wp = this.(TypeParamItemNode).getAWherePred() and
tbl = wp.getTypeBoundList() and
wp = any(WhereClause wc).getPredicate(i)
)
Copy link
Contributor

Choose a reason for hiding this comment

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

I feel like this case should simplify to tbl = this.(TypeParamItemNode).getWherePred(i).getTypeBoundList() (except that getWherePred(i) doesn't exist there). I don't feel strongly if this is a pain to change.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'll give it a try. I had that predicate before, but ran into non-monotonic recursion. But it should be doable as long as the getWherePred(i) is not actually used in path resolution itself.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I agree that what you propose is a lot cleaner, but the getWherePred on TypeParamItemNode would have to use rank and then we got non-monotonic recursion 😢

Copy link
Contributor

Choose a reason for hiding this comment

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

No problem, don't spend any more time on it!

)
}
Copy link
Preview

Copilot AI Aug 4, 2025

Choose a reason for hiding this comment

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

[nitpick] The getTypeBoundAt method uses magic numbers and has unclear indexing logic. Consider adding documentation to explain the indexing scheme where i=0 represents direct bounds and i>0 represents where clause predicates, or use more descriptive parameter names like source and boundIndex.

Copilot uses AI. Check for mistakes.


/**
* Gets the `index`th type bound of this type parameter, if any.
*
* This includes type bounds directly on this type parameter and bounds from
* any `where` clauses for this type parameter.
*/
TypeBound getTypeBound(int index) {
result = rank[index + 1](int i, int j | | this.getTypeBoundAt(i, j) order by i, j)
}

/**
* Gets a type bound of this type parameter.
*
* This includes type bounds directly on this type parameter and bounds from
* any `where` clauses for this type parameter.
*/
TypeBound getATypeBound() {
// NOTE: This predicate is used in path resolution, so it can not be
// defined using `getTypeBound` as that would cause non-monotonic
// recursion due to the `rank`.
result = this.getTypeBoundAt(_, _)
}

override string toAbbreviatedString() { result = this.getName().getText() }

override string toStringImpl() { result = this.getName().getText() }
Expand Down
22 changes: 5 additions & 17 deletions rust/ql/lib/codeql/rust/internal/PathResolution.qll
Original file line number Diff line number Diff line change
Expand Up @@ -791,9 +791,7 @@ private class StructItemNode extends TypeItemNode instanceof Struct {

class TraitItemNode extends ImplOrTraitItemNode, TypeItemNode instanceof Trait {
pragma[nomagic]
Path getABoundPath() {
result = super.getTypeBoundList().getABound().getTypeRepr().(PathTypeRepr).getPath()
}
Path getABoundPath() { result = super.getATypeBound().getTypeRepr().(PathTypeRepr).getPath() }

pragma[nomagic]
ItemNode resolveABound() { result = resolvePath(this.getABoundPath()) }
Expand Down Expand Up @@ -924,7 +922,8 @@ private class BlockExprItemNode extends ItemNode instanceof BlockExpr {
}

class TypeParamItemNode extends TypeItemNode instanceof TypeParam {
private WherePred getAWherePred() {
/** Gets a where predicate for this type parameter, if any */
WherePred getAWherePred() {
exists(ItemNode declaringItem |
this = resolveTypeParamPathTypeRepr(result.getTypeRepr()) and
result = declaringItem.getADescendant() and
Expand All @@ -933,13 +932,7 @@ class TypeParamItemNode extends TypeItemNode instanceof TypeParam {
}

pragma[nomagic]
Path getABoundPath() {
exists(TypeBoundList tbl | result = tbl.getABound().getTypeRepr().(PathTypeRepr).getPath() |
tbl = super.getTypeBoundList()
or
tbl = this.getAWherePred().getTypeBoundList()
)
}
Path getABoundPath() { result = super.getATypeBound().getTypeRepr().(PathTypeRepr).getPath() }

pragma[nomagic]
ItemNode resolveABound() { result = resolvePath(this.getABoundPath()) }
Expand All @@ -956,12 +949,7 @@ class TypeParamItemNode extends TypeItemNode instanceof TypeParam {
* ```
*/
cached
predicate hasTraitBound() {
Stages::PathResolutionStage::ref() and
exists(this.getABoundPath())
or
exists(this.getAWherePred())
}
predicate hasTraitBound() { Stages::PathResolutionStage::ref() and exists(this.getABoundPath()) }

/**
* Holds if this type parameter has no trait bound. Examples:
Expand Down
6 changes: 3 additions & 3 deletions rust/ql/lib/codeql/rust/internal/TypeInference.qll
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ private module Input2 implements InputSig2 {
TypeMention getABaseTypeMention(Type t) { none() }

TypeMention getATypeParameterConstraint(TypeParameter tp) {
result = tp.(TypeParamTypeParameter).getTypeParam().getTypeBoundList().getABound().getTypeRepr()
result = tp.(TypeParamTypeParameter).getTypeParam().getATypeBound().getTypeRepr()
or
result = tp.(SelfTypeParameter).getTrait()
or
Expand Down Expand Up @@ -184,12 +184,12 @@ private module Input2 implements InputSig2 {
exists(Trait trait |
abs = trait and
condition = trait and
constraint = trait.getTypeBoundList().getABound().getTypeRepr()
constraint = trait.getATypeBound().getTypeRepr()
)
or
// trait bounds on type parameters
exists(TypeParam param |
abs = param.getTypeBoundList().getABound() and
abs = param.getATypeBound() and
condition = param and
constraint = abs.(TypeBound).getTypeRepr()
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ multipleCallTargets
| main.rs:118:9:118:11 | f(...) |
| proc_macro.rs:9:5:11:5 | ...::new(...) |
multiplePathResolutions
| main.rs:626:3:626:12 | proc_macro |
| main.rs:632:7:632:16 | proc_macro |
| main.rs:635:7:635:16 | proc_macro |
| main.rs:641:3:641:12 | proc_macro |
| main.rs:647:7:647:16 | proc_macro |
| main.rs:650:7:650:16 | proc_macro |
15 changes: 15 additions & 0 deletions rust/ql/test/library-tests/path-resolution/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,21 @@ mod m15 {
}
} // I82

#[rustfmt::skip]
trait Trait3<
TT // ITT
>
where
Self: Trait1, // $ item=ITrait3 item=I79
TT: Trait1, // $ item=ITT item=I79
{
fn f(&self, tt: TT) { // $ item=ITT
Self::g(self); // $ item=I80
TT::g(&tt); // $ item=I80
self.g(); // $ item=I80
}
} // ITrait3

struct S; // I81

#[rustfmt::skip]
Expand Down
Loading