Skip to content

Commit e7ba741

Browse files
committed
Rust: Adjust the inferred type of string literals
1 parent e5b4a15 commit e7ba741

File tree

3 files changed

+274
-139
lines changed

3 files changed

+274
-139
lines changed

rust/ql/lib/codeql/rust/internal/TypeInference.qll

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1020,14 +1020,12 @@ private Type inferTryExprType(TryExpr te, TypePath path) {
10201020
}
10211021

10221022
pragma[nomagic]
1023-
private StructType inferLiteralType(LiteralExpr le) {
1023+
private Type inferLiteralType(LiteralExpr le, TypePath path) {
1024+
path.isEmpty() and
10241025
exists(Builtins::BuiltinType t | result = TStruct(t) |
10251026
le instanceof CharLiteralExpr and
10261027
t instanceof Builtins::Char
10271028
or
1028-
le instanceof StringLiteralExpr and
1029-
t instanceof Builtins::Str
1030-
or
10311029
le =
10321030
any(NumberLiteralExpr ne |
10331031
t.getName() = ne.getSuffix()
@@ -1045,6 +1043,14 @@ private StructType inferLiteralType(LiteralExpr le) {
10451043
le instanceof BooleanLiteralExpr and
10461044
t instanceof Builtins::Bool
10471045
)
1046+
or
1047+
le instanceof StringLiteralExpr and
1048+
(
1049+
path.isEmpty() and result = TRefTypeParameter()
1050+
or
1051+
path = TypePath::singleton(TRefTypeParameter()) and
1052+
result = TStruct(any(Builtins::Str s))
1053+
)
10481054
}
10491055

10501056
pragma[nomagic]
@@ -1578,8 +1584,7 @@ private module Cached {
15781584
or
15791585
result = inferTryExprType(n, path)
15801586
or
1581-
result = inferLiteralType(n) and
1582-
path.isEmpty()
1587+
result = inferLiteralType(n, path)
15831588
or
15841589
result = inferAsyncBlockExprRootType(n) and
15851590
path.isEmpty()

rust/ql/test/library-tests/type-inference/main.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1413,7 +1413,7 @@ mod builtins {
14131413
let z = x + y; // $ type=z:i32 method=add
14141414
let z = x.abs(); // $ method=abs $ type=z:i32
14151415
let c = 'c'; // $ type=c:char
1416-
let hello = "Hello"; // $ type=hello:str
1416+
let hello = "Hello"; // $ type=hello:&T.str
14171417
let f = 123.0f64; // $ type=f:f64
14181418
let t = true; // $ type=t:bool
14191419
let f = false; // $ type=f:bool
@@ -2086,10 +2086,10 @@ mod loops {
20862086
let vals4: [u64; 3] = [1; 3]; // $ type=vals4:[T;...].u64
20872087
for u in vals4 {} // $ type=u:u64
20882088

2089-
let mut strings1 = ["foo", "bar", "baz"]; // $ type=strings1:[T;...].str
2089+
let mut strings1 = ["foo", "bar", "baz"]; // $ type=strings1:[T;...].&T.str
20902090
for s in &strings1 {} // $ MISSING: type=s:&T.str
20912091
for s in &mut strings1 {} // $ MISSING: type=s:&T.str
2092-
for s in strings1 {} // $ type=s:str
2092+
for s in strings1 {} // $ type=s:&T.str
20932093

20942094
let strings2 = // $ type=strings2:[T;...].String
20952095
[

0 commit comments

Comments
 (0)