#!/usr/bin/perl -w use Getopt::Std; use strict; our ($opt_A, $opt_n); getopts('nA'); my $dry_run = $opt_n; my $add_braces = !$opt_A; my $any_bad = 0; my @files = @ARGV; undef $/; unless (@files) { @files = (grep /\.(cc|h)$/ && !/(^|\/)prebuilt\//, split /\n/, `git ls-files`); } sub rebrace($$$) { my ($condition, $indent, $body) = @_; my $orig = "$condition$body"; # Don't add braces if it's only two lines. return $orig unless $orig =~ /\n.*\n.*\n/; # Don't add braces if the "body" consists of only comments. return $orig unless $body =~ m&^\s++(?!//)&s; return "$condition$indent\{\n$body$indent\}\n"; } for my $f (@files) { open F, "<", $f or die "Can't read $f\n"; my $old = $_ = ; close F; # Eliminate braces around one-line blocks. s&^( +(?:if|while|for|do|else)\b[^\n]*)\n +{\n( *[^/ }][^\n]*)\n +}$&$1\n$2&msg; # Add braces in blocks that need them. s/# $1 = the keyword and condition ( # $2 = first-line indent ^(\s+) (?:if|while|for|do|else)\b \s* # $3 = nested parenthesised expression, possibly multi-line ( \( (?: [^()]* (?3))* [^()]* \) ) \s*\n ) # $4 = the body ( # Higher indent than the keyword. \2 \s++ # Not another flow control statement or braces (?! { | (?:if|while|for|do|else)\b) [^\n]*\n # And possibly more lines of higher indent than the keyword (?: \2 \s+ [^\n]* \n)* ) /rebrace($1,$2,$4)/egsmx if $add_braces; # return is not a function, eliminate totally enclosing parentheses. # This part handles parenthese-less payloads. while (/^( *)return \(([^()]+)\);/sm) { # Done this roundabout way to properly unindent multiline blocks. my $prev = "$`$1return "; my $next = ";$'"; my $cur = $2; $cur =~ s/\n /\n/sg; $_ = "$prev$cur$next"; } # return (x) where x contains parentheses. # Looks like no one told Larry Wall properties of regular expression, # including the part where they can't do arbitrarily nested parentheses. while (/^(\s*)return\s+ \(( (?: [^()]*+ (\( (?: [^()]++ | (?3) )* \)) )+ [^()]*+ )\);/sxm) { my $prev = "$`$1return "; my $next = ";$'"; my $cur = "$2"; $cur =~ s/\n /\n/sg; $_ = "$prev$cur$next"; } if ($old ne $_) { print "$f\n"; $any_bad = 1; if (!$dry_run) { open F, ">", $f or die "Can't write $f\n"; print F; close F; } } } exit 1 if ($dry_run and $any_bad);