]> git.ipfire.org Git - thirdparty/man-pages.git/commitdiff
bash_aliases: Increase robustness of sed_rm_ccomments()
authorAlejandro Colomar <alx@kernel.org>
Tue, 23 May 2023 14:29:34 +0000 (16:29 +0200)
committerAlejandro Colomar <alx@kernel.org>
Tue, 23 May 2023 23:13:51 +0000 (01:13 +0200)
Thanks to perl(1), we can use a non-greedy match to remove several
C89-style comments in the same line.  And by splitting (and slightly
modifying) the other sed(1) call, we can handle multi-line comments that
start in the same line that the previous one ends.

Now the only remaining issue is nested comments, but that's rare, so
let's ignore it for now.

$ cat com.c
/* let's see */ int foo/*how about here?*/; // meh
int bar; /* Let's see
how this
behaves */ int baz; /* like this?
like that! */ int qwe; // asdasd

$ sed_rm_ccomments <com.c
 int foo;
int bar;
 int baz;
 int qwe;

Here's what can and will be problematic:

// /*
int foo;
/* */

Signed-off-by: Alejandro Colomar <alx@kernel.org>
scripts/bash_aliases

index 5c0458402e8f4f561a67be860df1590f28ed2ad1..e461707c8c2311ef1f586a38e0e6b02d344303ea 100644 (file)
@@ -23,14 +23,15 @@ EX_USAGE=64;
 #      C
 
 #  sed_rm_ccomments()  removes C comments.
-# It can't handle multiple comments in a single line correctly,
-# nor mixed or embedded //... and /*...*/ comments.
+# It can't handle mixed //... and /*...*/ comments.
 # Use as a filter (see man_lsfunc() in this file).
 
 sed_rm_ccomments()
 {
-       sed 's%/\*.*\*/%%' \
-       |sed -E '\%/\*%,\%\*/%{\%(\*/|/\*)%!d; s%/\*.*%%; s%.*\*/%%;}' \
+       perl -p -e 's%/\*.*?\*/%%g' \
+       |sed -E '\%/\*%, \%\*/% {\%(\*/|/\*)%!d}' \
+       |sed -E '\%/\*% {s%/\*.*%%; n; s%.*\*/%%;}' \
+       |sed -E '\%/\*% {s%/\*.*%%; n; s%.*\*/%%;}' \
        |sed 's%//.*%%';
 }