C++: Add test for C++20 implicit array sizes

Implement NewArrayExpr.getArraySize()
This commit is contained in:
Calum Grant
2024-07-11 11:22:21 +01:00
parent 57efb84b98
commit 29df3cb5b3
5 changed files with 36 additions and 0 deletions

View File

@@ -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;

View File

@@ -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[] | |

View File

@@ -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

View File

@@ -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 |

View File

@@ -0,0 +1,4 @@
import cpp
from NewArrayExpr nae
select nae, nae.getArraySize()