xref: /freebsd/tools/tools/hcomp/hcomp.pl (revision e738085b)
1#!/usr/bin/perl -w
2#-
3# Copyright (c) 2003 Dag-Erling Smørgrav
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions
8# are met:
9# 1. Redistributions of source code must retain the above copyright
10#    notice, this list of conditions and the following disclaimer
11#    in this position and unchanged.
12# 2. Redistributions in binary form must reproduce the above copyright
13#    notice, this list of conditions and the following disclaimer in the
14#    documentation and/or other materials provided with the distribution.
15# 3. The name of the author may not be used to endorse or promote products
16#    derived from this software without specific prior written permission.
17#
18# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28#
29#
30
31use strict;
32use Getopt::Std;
33
34our $opt_b;
35our $opt_v;
36
37sub hcomp($)
38{
39    my $fn = shift;
40
41    local *FILE;
42    my $header;
43
44    warn("$fn\n")
45	if ($opt_v);
46
47    open(FILE, "<", $fn)
48	or die("$fn: $!\n");
49    $header = join('', <FILE>);
50    close(FILE);
51
52    # Remove comments
53    $header =~ s|/\*.*?\*/||gs;
54    $header =~ s|//.*$||gm;
55
56    # Collapse preprocessor directives
57    while ($header =~ s|(\n\#.*?)\\\n|$1|gs) {
58	# nothing
59    }
60
61    # Remove superfluous whitespace
62    $header =~ s|^\s+||s;
63    $header =~ s|^\s+||gm;
64    $header =~ s|\s+$||s;
65    $header =~ s|\s+$||gm;
66    $header =~ s|\n+|\n|gs;
67    $header =~ s|[ \t]+| |gm;
68
69    open(FILE, ">", "$fn.new")
70	or die("$fn.new: $!\n");
71    print(FILE $header);
72    close(FILE);
73
74    rename($fn, "$fn.$opt_b")
75	if defined($opt_b);
76    rename("$fn.new", $fn);
77}
78
79sub usage()
80{
81    print(STDERR "usage: hcomp [-b ext] file ...\n");
82    exit(1);
83}
84
85MAIN:{
86    my %opts;
87    getopts('b:v')
88	or usage();
89    foreach (@ARGV) {
90	hcomp($_);
91    }
92}
93