Peeter Joot's (OLD) Blog.

Math, physics, perl, and programming obscurity.

extract a parameter from a function call, and add it as a parameter to another.

Posted by peeterjoot on September 15, 2009

Here’s a fun change using the same evaluated regular expression “template” used in a few previous posts.  The object is to find the start and end of a function body (knowing the coding conventions in force), if it has a function call of a certain name, extract the first parameter in that function call and add it to the last parameter of all calls (if any) of two other functions.

I’ll let the script speak for itself, since it’s only slightly different from the ones detailed in previous posts. I’ve commented the regular expressions used to find the function start/stop (using the /x modifer that allows spacesand comments in the expression).

#!/usr/bin/perl

while (<>)
{
   $p .= $_ ;
}

$p =~ s/
(           # begin capture
^{          # match newline-brace-start
.*?         # other stuff but not greedy.
^}          # brace end at the beginning of the line
\s*$        # followed by nothing interesting (opt spaces then newline)
)           # end capture
/foo("$1")/smegx ;
print $p ;

exit ;

sub foo
{
   my $s = "@_" ;

   # find and extract the first parameter
   if ( $s =~ /TraceEntry\d* *\( *(.*?),/m )
   {
      my $tp = $1 ;

      # change any calls like: ASSERT_NONNULL(..., 0 ) to ASSERT_NONNULL( $tp )
      $s =~ s/(^ *ASSERT_NONNULL.*?), *0 *\) *; *$/$1, $tp ) ;/mg ;

      # change any calls like: ASSERT_THIS( 0 ) to ASSERT_THIS( $tp )
      $s =~ s/^( *ASSERT_THIS) *\( *0 *\) *; *$/$1( $tp ) ;/mg ;
   }

   return "$s" ;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: