| 1 |
#!/usr/bin/env perl |
| 2 |
# |
| 3 |
# Post-process files generated by protoc-c to remove anonymous unions. |
| 4 |
# Works on the generated files but probably little else. |
| 5 |
|
| 6 |
use warnings; |
| 7 |
use strict; |
| 8 |
|
| 9 |
sub unanon { |
| 10 |
my $hfile = shift; |
| 11 |
my $cfile = shift; |
| 12 |
my ($fh, $content); |
| 13 |
my %members; |
| 14 |
|
| 15 |
open $fh, "<", $hfile or die $!; |
| 16 |
local $/; # enable localized slurp mode |
| 17 |
$content = <$fh>; |
| 18 |
close $fh; |
| 19 |
|
| 20 |
# Detect and replace anonymous unions in .h file. |
| 21 |
# Assumes there is only one anonymous union in scope. |
| 22 |
while ($content =~ s/^(struct\s+(\w+)[^}]+)(union\s+{([^}]+)}\s*);/$1$3 u;/sm) { |
| 23 |
my $s = $2; |
| 24 |
my $u = $4; |
| 25 |
$u =~ s:/\*((?!\*/).)*\*/::sg; |
| 26 |
foreach (split(/\n+/, $u)) { |
| 27 |
if (/^.*\s+\**([^;]+);/) { |
| 28 |
$members{$1} = $s; |
| 29 |
} |
| 30 |
} |
| 31 |
} |
| 32 |
open $fh, ">", $hfile or die $!; |
| 33 |
print $fh $content; |
| 34 |
close $fh; |
| 35 |
|
| 36 |
# Replace anonymous union access in generated .c file. |
| 37 |
open $fh, "<", $cfile or die $!; |
| 38 |
$content = <$fh>; |
| 39 |
close $fh; |
| 40 |
|
| 41 |
while (my ($key, $val) = each %members) { |
| 42 |
# We only support access via offsetof() |
| 43 |
$content =~ s/offsetof\($val, $key\)/offsetof($val, u.$key)/g; |
| 44 |
} |
| 45 |
open $fh, ">", $cfile or die $!; |
| 46 |
print $fh $content; |
| 47 |
close $fh; |
| 48 |
} |
| 49 |
|
| 50 |
unanon(@ARGV); |