Match structure usage

In this example we address the case where the type of the variables we want to match the usage is in fact a structure. The study of the following semantic patch will teach you about how to impose constraints on expressions and specifically how to
specify the type of a variable when it is a structure.

@@
struct mystruct1 x;
@@
 
* x

In a previous example we covered how to specify type constraints for identifer-like expressions using idexpression. Here we extend that to all expressions. Indeed “struct mystruct1 x;” defines an expression metavariable whose type is “struct mystruct1”.

“* x” tells Coccinelle to match every occurrence respecting this type constraint.

Here is the file we will be applying the semantic patch to:

struct mystruct1 {
	char field1;
	int  field2;
};
 
struct mystruct2 {
	char field1;
	int  field2;
};
 
int f1() {
	int var = 0;
	return var;
}
 
int f2() {
	int var;
	var = 0;
	return var;
}
 
long f3() {
	long bar = 0;
	struct mystruct1 s;
	s.field1 = 0;
	s.field2 = 1;
	return bar;
}
 
long f4() {
	long bar;
	struct mystruct2 s;
	s.field1 = 0;
	s.field2 = 1;
	bar = 0;
	return bar;
}

Here is the resulting output:

--- tuto03.c
+++ /tmp/cocci-output-3755-2be550-tuto03.c
@@ -22,8 +22,6 @@ int f2() {
 long f3() {
 	long bar = 0;
 	struct mystruct1 s;
-	s.field1 = 0;
-	s.field2 = 1;
 	return bar;
 }

As expected, the matched lines are exactly the uses of variables of type “struct mystruct1”. In particular, note that here “mystruct1” is interpreted as the actual name of the structure in the source code.