On 27 June 2011 16:21, Ajay Panyala <[email protected]> wrote:
> Hello
> Is something like the following possible.
>
> Original code :
> ...
> // some comment
> foo(x,y);
> .....
> foo(x,y)
> The code should be transformed after applying a patch
> such that only the occurrence of foo(...) with the comment
> above it should be transformed, i.e
> The code after the transformation should look like
> ...
> // some comment
> bar(x,y,z)
> ...
> foo(x,y)
> The second call to foo(..) should remain untouched.
>
> If possible, how should a patch be specified to handle this case.
You can make the comment into a statement by letting it be the
argument(s) in a (dummy) macro. The following is a quick
test of conditionally changing printf into fprintf(stderr only when
preceded by a debug comment.
(hlovdal) localhost:/download/2011/06_jun/cocci>cat main.c
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
// debug print
printf("argc = %d\n", argc);
for (i=0; i<argc; i++) {
printf("argv[i] = %s\n", argv[i]);
}
}
(hlovdal) localhost:/download/2011/06_jun/cocci>sed 's@\(// debug
print.*\)@COMMENT_MACRO("\1");@' main.c > tmp.c
(hlovdal) localhost:/download/2011/06_jun/cocci>diff -u main.c tmp.c
--- main.c 2011-06-28 22:45:12.883225594 +0200
+++ tmp.c 2011-06-28 23:07:44.849522682 +0200
@@ -3,7 +3,7 @@
int main(int argc, char *argv[])
{
int i;
- // debug print
+ COMMENT_MACRO("// debug print");
printf("argc = %d\n", argc);
for (i=0; i<argc; i++) {
(hlovdal) localhost:/download/2011/06_jun/cocci>cat macro.h
#define COMMENT_MACRO(x)
(hlovdal) localhost:/download/2011/06_jun/cocci>cat
change_if_after_comment.cocci
@@
expression x, y;
@@
COMMENT_MACRO(...);
-printf(x, y);
+fprintf(stderr, x, y);
(hlovdal) localhost:/download/2011/06_jun/cocci>spatch -sp_file
change_if_after_comment.cocci -macro_file macro.h tmp.c
init_defs_builtins: /usr/share/coccinelle/standard.h
init_defs: macro.h
HANDLING: tmp.c
diff =
--- tmp.c 2011-06-28 23:07:44.849522682 +0200
+++ /tmp/cocci-output-620-e129f9-tmp.c 2011-06-28 23:07:53.848986434 +0200
@@ -4,7 +4,7 @@ int main(int argc, char *argv[])
{
int i;
COMMENT_MACRO("// debug print");
- printf("argc = %d\n", argc);
+ fprintf(stderr, "argc = %d\n", argc);
for (i=0; i<argc; i++) {
printf("argv[i] = %s\n", argv[i]);
(hlovdal) localhost:/download/2011/06_jun/cocci>
The sed command will only match comments excactly, you might want to
match wider. To convert back from macro to comment run
sed 's/COMMENT_MACRO("\(.*\)");/\1/' filename.c
BR Håkon Løvdal
_______________________________________________
Cocci mailing list
[email protected]
http://lists.diku.dk/mailman/listinfo/cocci
(Web access from inside DIKUs LAN only)