Skip to content

Commit

Permalink
C++: Add test for C++20 implicit array sizes
Browse files Browse the repository at this point in the history
Implement NewArrayExpr.getArraySize()
  • Loading branch information
calumgrant committed Jul 11, 2024
1 parent 57efb84 commit 29df3cb
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 0 deletions.
10 changes: 10 additions & 0 deletions cpp/ql/lib/semmle/code/cpp/exprs/Expr.qll
Original file line number Diff line number Diff line change
Expand Up @@ -949,6 +949,16 @@ class NewArrayExpr extends NewOrNewArrayExpr, @new_array_expr {
* gives nothing, as the 10 is considered part of the type.
*/
Expr getExtent() { result = this.getChild(2) }

/**
* Gets the number of elements in the array, if available.
*
* For example, `new int[]{1,2,3}` has an array size of 3.
*/
int getArraySize() {
result = this.getAllocatedType().(ArrayType).getArraySize() or
result = this.getInitializer().(ArrayAggregateLiteral).getArraySize()
}
}

private class TDeleteOrDeleteArrayExpr = @delete_expr or @delete_array_expr;
Expand Down
6 changes: 6 additions & 0 deletions cpp/ql/test/library-tests/array_sizes/arr2.expected
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
| file://:0:0:0:0 | char[6] | 6 |
| file://:0:0:0:0 | char[26] | 26 |
| file://:0:0:0:0 | char[] | |
| file://:0:0:0:0 | const char[6] | 6 |
| file://:0:0:0:0 | double[0] | 0 |
| file://:0:0:0:0 | double[3] | 3 |
| file://:0:0:0:0 | double[4] | 4 |
| file://:0:0:0:0 | double[] | |
| file://:0:0:0:0 | int[1] | 1 |
| file://:0:0:0:0 | int[11] | 11 |
| file://:0:0:0:0 | long[] | |
Expand Down
10 changes: 10 additions & 0 deletions cpp/ql/test/library-tests/array_sizes/implicit_sizes.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// semmle-extractor-options: -std=c++20
double a1[]{1,2,3};
double* p1 = new double[]{1,2,3};
double* p2 = new double[0]{};
double* p3 = new double[]{};
char c[]{"Hello"};
char* d = new char[]{"Hello"};
double a2[](1,2,3);
double* p4 = new double[](1,2,3);
double* p5 = new double[4]{1,2}; // Size mismatch
6 changes: 6 additions & 0 deletions cpp/ql/test/library-tests/array_sizes/new.expected
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
| implicit_sizes.cpp:3:14:3:32 | new[] | 3 |
| implicit_sizes.cpp:4:14:4:28 | new[] | 0 |
| implicit_sizes.cpp:5:14:5:27 | new[] | 0 |
| implicit_sizes.cpp:7:11:7:29 | new[] | 6 |
| implicit_sizes.cpp:9:14:9:32 | new[] | 3 |
| implicit_sizes.cpp:10:14:10:31 | new[] | 4 |
4 changes: 4 additions & 0 deletions cpp/ql/test/library-tests/array_sizes/new.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import cpp

from NewArrayExpr nae
select nae, nae.getArraySize()

0 comments on commit 29df3cb

Please sign in to comment.