summaryrefslogtreecommitdiffstats
path: root/build/flags-if.sh
blob: f7b4f33917fd354a7306c7f2013bf9d08ec5b57e (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/bin/sh

# Copyright © Tavian Barnes <tavianator@tavianator.com>
# SPDX-License-Identifier: 0BSD

# Add flags to a makefile if a build succeeds.  Source files can specify their
# own flags with lines like
#
#     /// _CFLAGS += -Wmissing-variable-declarations
#
# which will be added to the makefile on success, or lines like
#
#     /// -Werror
#
# which are just used for the current file.  Lines like
#
#     /// ---
#
# separate groups of flags, to try multiple ways to achieve something, e.g.
#
#     /// CFLAGS += -pthread
#     /// ---
#     /// LDLIBS += -lpthread

set -eu

# Any new flags we're using
FLAGS=""
# Any new makefile lines we're printing
OUTPUT=""

# Check the existing flags so we don't add duplicates
OLD_FLAGS=" $XCPPFLAGS $XCFLAGS $XLDFLAGS $XLDLIBS "

add_flag() {
    case "$1" in
        -std=*)
            # Don't overwrite -std=* flags
            case "$OLD_FLAGS" in
                *\ -std=*)
                    return 1
                    ;;
            esac
            ;;
        *)
            if [ "${OLD_FLAGS#* $1 }" != "$OLD_FLAGS" ]; then
                return 1
            fi
            ;;
    esac

    FLAGS="${FLAGS}${FLAGS:+ }$1"
}

try_cc() {
    build/cc.sh "$@" $FLAGS || return $?
    printf '%s' "$OUTPUT"
    exit
}

while IFS="" read -r line; do
    case "$line" in
        "/// "*)
            line="${line#/// }"
            ;;
        *)
            continue
            ;;
    esac

    case "$line" in
        ---)
            try_cc "$@" || :
            FLAGS=
            OUTPUT=
            ;;
        *=*)
            if add_flag "${line#*= }"; then
                OUTPUT="${OUTPUT}${line}
"
            fi
            ;;
        *)
            add_flag "$line" || :
            ;;
    esac
done <"$1"

try_cc "$@"