aboutsummaryrefslogtreecommitdiffstats
path: root/make/scripts/strip-c-comments.awk
blob: 4f35452b2ed14e3ccad95fcab7e5e38436f21e26 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/awk

BEGIN { ORS = "" ; C99=1 }

{ code = code $0 "\n" }

END {
    while ( length(code) )
    code = process( code )
}

function process( text )
{
    if ( C99 ) { 
        if ( match( text, /"|'|\/\*|\/\// ) ) {
            return span( text )
        }
    } else if ( match( text, /"|'|\/\*/ ) ) {
        return span( text )
    }
    print text
    return ""
}

function span( text , starter )
{
    print substr( text, 1, RSTART - 1 )
    starter = substr( text, RSTART, RLENGTH )
    text = substr( text, RSTART + RLENGTH )

    if ( "\"" == starter || "'" == starter ) {
        return quoted( text, starter )
    }
    if ( "//" == starter ) {
        return remove( text, "\n", "\n" )
    }
    ## Allow for
    ## /* foo *\
    ## /
    return remove( text, "\\*(\\\\\n)?/", " " )
}

function remove( text, ender, replacement )
{
    print replacement
    return substr( text, match(text, ender) + RLENGTH )
}

function quoted( text, starter )
{
    if ( "'" == starter ) {
        match( text, /^(\\.|[^'])*'/ )
    } else {
        match( text, /^(\\.|\?\?\/.|[^"])*"/ )
    }
    print starter substr( text, 1, RLENGTH )
    return substr( text, RSTART + RLENGTH )
}