-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Rust: Implement type inference for closures and calls to closures #20130
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
paldepind
wants to merge
3
commits into
github:main
Choose a base branch
from
paldepind:rust/type-inference-fn
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||||
---|---|---|---|---|---|---|---|---|
|
@@ -383,6 +383,17 @@ private predicate typeEquality(AstNode n1, TypePath prefix1, AstNode n2, TypePat | |||||||
prefix2.isEmpty() and | ||||||||
s = getRangeType(n1) | ||||||||
) | ||||||||
or | ||||||||
exists(ClosureExpr ce, int index | | ||||||||
n1 = ce and | ||||||||
n2 = ce.getParam(index).getPat() and | ||||||||
prefix1 = closureParameterPath(ce.getNumberOfParams(), index) and | ||||||||
prefix2.isEmpty() | ||||||||
) | ||||||||
or | ||||||||
n1.(ClosureExpr).getBody() = n2 and | ||||||||
prefix1 = closureReturnPath() and | ||||||||
prefix2.isEmpty() | ||||||||
} | ||||||||
|
||||||||
pragma[nomagic] | ||||||||
|
@@ -1435,6 +1446,120 @@ private Type inferForLoopExprType(AstNode n, TypePath path) { | |||||||
) | ||||||||
} | ||||||||
|
||||||||
/** | ||||||||
* An invoked expression, the target of a call that is either a local variable | ||||||||
* or a non-path expression. This means that the expression denotes a | ||||||||
* first-class function. | ||||||||
*/ | ||||||||
final private class InvokedClosureExpr extends Expr { | ||||||||
private CallExpr call; | ||||||||
|
||||||||
InvokedClosureExpr() { | ||||||||
call.getFunction() = this and | ||||||||
(not this instanceof PathExpr or this = any(Variable v).getAnAccess()) | ||||||||
} | ||||||||
|
||||||||
Type getTypeAt(TypePath path) { result = inferType(this, path) } | ||||||||
|
||||||||
CallExpr getCall() { result = call } | ||||||||
} | ||||||||
|
||||||||
private module InvokedClosureSatisfiesConstraintInput implements | ||||||||
SatisfiesConstraintInputSig<InvokedClosureExpr> | ||||||||
{ | ||||||||
predicate relevantConstraint(InvokedClosureExpr term, Type constraint) { | ||||||||
exists(term) and | ||||||||
constraint.(TraitType).getTrait() instanceof FnOnceTrait | ||||||||
} | ||||||||
} | ||||||||
|
||||||||
/** Gets the type of `ce` when viewed as an implementation of `FnOnce`. */ | ||||||||
private Type invokedClosureFnTypeAt(InvokedClosureExpr ce, TypePath path) { | ||||||||
SatisfiesConstraint<InvokedClosureExpr, InvokedClosureSatisfiesConstraintInput>::satisfiesConstraintType(ce, | ||||||||
_, path, result) | ||||||||
} | ||||||||
|
||||||||
/** Gets the path to a closure's return type. */ | ||||||||
private TypePath closureReturnPath() { | ||||||||
result = TypePath::singleton(TDynTraitTypeParameter(any(FnOnceTrait t).getOutputType())) | ||||||||
} | ||||||||
|
||||||||
/** Gets the path to a closure with arity `arity`s `index`th parameter type. */ | ||||||||
private TypePath closureParameterPath(int arity, int index) { | ||||||||
result = | ||||||||
TypePath::cons(TDynTraitTypeParameter(any(FnOnceTrait t).getTypeParam()), | ||||||||
TypePath::singleton(TTupleTypeParameter(arity, index))) | ||||||||
} | ||||||||
|
||||||||
/** Gets the path to the return type of the `FnOnce` trait. */ | ||||||||
private TypePath fnReturnPath() { | ||||||||
result = TypePath::singleton(TAssociatedTypeTypeParameter(any(FnOnceTrait t).getOutputType())) | ||||||||
} | ||||||||
|
||||||||
/** | ||||||||
* Gets the path to the parameter type of the `FnOnce` trait with arity `arity` | ||||||||
* and index `index`. | ||||||||
*/ | ||||||||
private TypePath fnParameterPath(int arity, int index) { | ||||||||
result = | ||||||||
TypePath::cons(TTypeParamTypeParameter(any(FnOnceTrait t).getTypeParam()), | ||||||||
TypePath::singleton(TTupleTypeParameter(arity, index))) | ||||||||
} | ||||||||
|
||||||||
pragma[nomagic] | ||||||||
private Type inferDynamicCallExprType(Expr n, TypePath path) { | ||||||||
exists(InvokedClosureExpr ce | | ||||||||
// Propagate the function's return type to the call expression | ||||||||
exists(TypePath path0 | result = invokedClosureFnTypeAt(ce, path0) | | ||||||||
n = ce.getCall() and | ||||||||
path = path0.stripPrefix(fnReturnPath()) | ||||||||
or | ||||||||
// Propagate the function's parameter type to the arguments | ||||||||
exists(int index | | ||||||||
n = ce.getCall().getArgList().getArg(index) and | ||||||||
path = path0.stripPrefix(fnParameterPath(ce.getCall().getNumberOfArgs(), index)) | ||||||||
) | ||||||||
) | ||||||||
or | ||||||||
// _If_ the invoked expression has the type of a closure, then we propagate | ||||||||
// the surrounding types into the closure. | ||||||||
exists(int arity, TypePath path0 | | ||||||||
ce.getTypeAt(TypePath::nil()).(DynTraitType).getTrait() instanceof FnOnceTrait | ||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This condition performs multiple method calls and type checks in sequence. Consider caching the result of
Suggested change
Copilot uses AI. Check for mistakes. Positive FeedbackNegative Feedback |
||||||||
| | ||||||||
// Propagate the type of arguments to the parameter types of closure | ||||||||
exists(int index | | ||||||||
n = ce and | ||||||||
arity = ce.getCall().getNumberOfArgs() and | ||||||||
result = inferType(ce.getCall().getArg(index), path0) and | ||||||||
path = closureParameterPath(arity, index).append(path0) | ||||||||
) | ||||||||
or | ||||||||
// Propagate the type of the call expression to the return type of the closure | ||||||||
n = ce and | ||||||||
arity = ce.getCall().getNumberOfArgs() and | ||||||||
result = inferType(ce.getCall(), path0) and | ||||||||
path = closureReturnPath().append(path0) | ||||||||
) | ||||||||
) | ||||||||
} | ||||||||
|
||||||||
pragma[nomagic] | ||||||||
private Type inferClosureExprType(AstNode n, TypePath path) { | ||||||||
exists(ClosureExpr ce | | ||||||||
n = ce and | ||||||||
path.isEmpty() and | ||||||||
result = TDynTraitType(any(FnOnceTrait t)) | ||||||||
or | ||||||||
n = ce and | ||||||||
path = TypePath::singleton(TDynTraitTypeParameter(any(FnOnceTrait t).getTypeParam())) and | ||||||||
result = TTuple(ce.getNumberOfParams()) | ||||||||
or | ||||||||
// Propagate return type annotation to body | ||||||||
n = ce.getBody() and | ||||||||
result = ce.getRetType().getTypeRepr().(TypeMention).resolveTypeAt(path) | ||||||||
) | ||||||||
} | ||||||||
|
||||||||
pragma[nomagic] | ||||||||
private Type inferCastExprType(CastExpr ce, TypePath path) { | ||||||||
result = ce.getTypeRepr().(TypeMention).resolveTypeAt(path) | ||||||||
|
@@ -2062,6 +2187,10 @@ private module Cached { | |||||||
or | ||||||||
result = inferForLoopExprType(n, path) | ||||||||
or | ||||||||
result = inferDynamicCallExprType(n, path) | ||||||||
or | ||||||||
result = inferClosureExprType(n, path) | ||||||||
or | ||||||||
result = inferCastExprType(n, path) | ||||||||
or | ||||||||
result = inferStructPatType(n, path) | ||||||||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
5 changes: 5 additions & 0 deletions
5
rust/ql/src/change-notes/2025-07-28-type-inference-closures.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
category: minorAnalysis | ||
--- | ||
* Type inference now supports closures, calls to closures, and trait bounds | ||
sing the `FnOnce` trait. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
/// Tests for type inference for closures and higher-order functions. | ||
|
||
mod simple_closures { | ||
pub fn test() { | ||
// A simple closure without type annotations or invocations. | ||
let my_closure = |a, b| a && b; | ||
|
||
let x: i64 = 1i64; // $ type=x:i64 | ||
let add_one = |n| n + 1i64; // $ target=add | ||
let _y = add_one(x); // $ type=_y:i64 | ||
|
||
// The type of `x` is inferred from the closure's argument type. | ||
let x = Default::default(); // $ type=x:i64 target=default | ||
let add_zero = |n: i64| n; | ||
let _y = add_zero(x); // $ type=_y:i64 | ||
|
||
let _get_bool = || -> bool { | ||
// The return type annotation on the closure lets us infer the type of `b`. | ||
let b = Default::default(); // $ type=b:bool target=default | ||
b | ||
}; | ||
|
||
// The parameter type of `id` is inferred from the argument. | ||
let id = |b| b; // $ type=b:bool | ||
let _b = id(true); // $ type=_b:bool | ||
|
||
// The return type of `id2` is inferred from the type of the call expression. | ||
let id2 = |b| b; | ||
let arg = Default::default(); // $ target=default type=arg:bool | ||
let _b2: bool = id2(arg); // $ type=_b2:bool | ||
} | ||
} | ||
|
||
mod fn_once_trait { | ||
fn return_type<F: FnOnce(bool) -> i64>(f: F) { | ||
let _return = f(true); // $ type=_return:i64 | ||
} | ||
|
||
fn argument_type<F: FnOnce(bool) -> i64>(f: F) { | ||
let arg = Default::default(); // $ target=default type=arg:bool | ||
f(arg); | ||
} | ||
|
||
fn apply<A, B, F: FnOnce(A) -> B>(f: F, a: A) -> B { | ||
f(a) | ||
} | ||
|
||
fn apply_two(f: impl FnOnce(i64) -> i64) -> i64 { | ||
f(2) | ||
} | ||
|
||
fn test() { | ||
let f = |x: bool| -> i64 { | ||
if x { | ||
1 | ||
} else { | ||
0 | ||
} | ||
}; | ||
let _r = apply(f, true); // $ target=apply type=_r:i64 | ||
|
||
let f = |x| x + 1; // $ MISSING: type=x:i64 target=add | ||
let _r2 = apply_two(f); // $ target=apply_two type=_r2:i64 | ||
} | ||
} | ||
|
||
mod dyn_fn_once { | ||
fn apply_boxed<A, B, F: FnOnce(A) -> B + ?Sized>(f: Box<F>, arg: A) -> B { | ||
f(arg) | ||
} | ||
|
||
fn apply_boxed_dyn<A, B>(f: Box<dyn FnOnce(A) -> B>, arg: A) { | ||
let _r1 = apply_boxed(f, arg); // $ target=apply_boxed type=_r1:B | ||
let _r2 = apply_boxed(Box::new(|_: i64| true), 3); // $ target=apply_boxed target=new type=_r2:bool | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[nitpick] The condition
call.getFunction() = this
could be inefficient as it requires checking all CallExpr nodes. Consider using a more targeted approach or adding an index if this becomes a performance bottleneck.Copilot uses AI. Check for mistakes.