aboutsummaryrefslogtreecommitdiff
path: root/src/makefile/conditional.rs
blob: bf373bd2e707d86b5551e9140f8b109e3a5d1ebc (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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
use super::token::TokenString;

pub(crate) enum ConditionalLine {
    /// spelled "ifeq"
    IfEqual(TokenString, TokenString),
    /// spelled "ifneq"
    IfNotEqual(TokenString, TokenString),
    /// spelled "ifdef"
    IfDefined(String),
    /// spelled "ifndef"
    IfNotDefined(String),
    /// spelled "else"
    Else,
    /// spelled "else condition"
    ElseIf(Box<ConditionalLine>),
    /// spelled "endif"
    EndIf,
}

pub(crate) enum ConditionalState {
    /// we saw a conditional, the condition was true, we're executing now
    /// and if we hit an else we will start SkippingUntilEndIf
    Executing,
    /// we saw a conditional, the condition was false, we're ignoring now
    /// and if we hit an else we'll start executing
    /// (or if it's an else if we'll check the condition)
    SkippingUntilElseOrEndIf,
    /// we saw a conditional, the condition was true, we executed, and now we hit an else
    /// so we don't need to stop and evaluate new conditions, because we straight up do
    /// not care
    SkippingUntilEndIf,
}

impl ConditionalState {
    pub(crate) const fn skipping(&self) -> bool {
        match self {
            Self::Executing => false,
            Self::SkippingUntilElseOrEndIf | Self::SkippingUntilEndIf => true,
        }
    }
}

pub(crate) enum ConditionalStateAction {
    Push(ConditionalState),
    Replace(ConditionalState),
    Pop,
}

impl ConditionalStateAction {
    pub(crate) fn apply_to(self, stack: &mut Vec<ConditionalState>) {
        match self {
            Self::Push(state) => stack.push(state),
            Self::Replace(state) => match stack.last_mut() {
                Some(x) => *x = state,
                None => panic!("applying Replace on an empty condition stack"),
            },
            Self::Pop => {
                stack.pop();
            }
        }
    }
}

fn decode_condition_args(line_body: &str) -> Option<(TokenString, TokenString)> {
    let tokens: TokenString = line_body.parse().ok()?;
    let (mut arg1, mut arg2) = if tokens.starts_with("(") && tokens.ends_with(")") {
        let mut tokens = tokens;
        tokens.strip_prefix("(");
        tokens.strip_suffix(")");
        tokens.split_once(',')?
    } else {
        // TODO see if i really need to implement potentially-mixed-quoted args
        return None;
    };
    arg1.trim_end();
    arg2.trim_start();
    Some((arg1, arg2))
}

impl ConditionalLine {
    pub(crate) fn from(
        line: &str,
        expand_macro: impl Fn(&TokenString) -> anyhow::Result<String>,
    ) -> anyhow::Result<Option<Self>> {
        Ok(Some(if let Some(line) = line.strip_prefix("ifeq ") {
            match decode_condition_args(line) {
                Some((arg1, arg2)) => Self::IfEqual(arg1, arg2),
                None => return Ok(None),
            }
        } else if let Some(line) = line.strip_prefix("ifneq ") {
            match decode_condition_args(line) {
                Some((arg1, arg2)) => Self::IfNotEqual(arg1, arg2),
                None => return Ok(None),
            }
        } else if let Some(line) = line.strip_prefix("ifdef ") {
            Self::IfDefined(expand_macro(&line.parse()?)?)
        } else if let Some(line) = line.strip_prefix("ifndef ") {
            Self::IfNotDefined(expand_macro(&line.parse()?)?)
        } else if line == "else" {
            Self::Else
        } else if let Some(line) = line.strip_prefix("else ") {
            match Self::from(line, expand_macro)? {
                Some(sub_condition) => Self::ElseIf(Box::new(sub_condition)),
                None => return Ok(None),
            }
        } else if line == "endif" {
            Self::EndIf
        } else {
            return Ok(None);
        }))
    }

    pub(crate) fn action(
        &self,
        current_state: Option<&ConditionalState>,
        is_macro_defined: impl Fn(&str) -> bool,
        expand_macro: impl Fn(&TokenString) -> anyhow::Result<String>,
    ) -> anyhow::Result<ConditionalStateAction> {
        use ConditionalState as State;
        use ConditionalStateAction as Action;
        Ok(match self {
            Self::IfEqual(arg1, arg2) => {
                let arg1 = expand_macro(arg1)?;
                let arg2 = expand_macro(arg2)?;
                if arg1 == arg2 {
                    Action::Push(State::Executing)
                } else {
                    Action::Push(State::SkippingUntilElseOrEndIf)
                }
            }
            Self::IfNotEqual(arg1, arg2) => {
                let arg1 = expand_macro(arg1)?;
                let arg2 = expand_macro(arg2)?;
                if arg1 == arg2 {
                    Action::Push(State::SkippingUntilElseOrEndIf)
                } else {
                    Action::Push(State::Executing)
                }
            }
            Self::IfDefined(name) => {
                if is_macro_defined(name) {
                    Action::Push(State::Executing)
                } else {
                    Action::Push(State::SkippingUntilElseOrEndIf)
                }
            }
            Self::IfNotDefined(name) => {
                if is_macro_defined(name) {
                    Action::Push(State::SkippingUntilElseOrEndIf)
                } else {
                    Action::Push(State::Executing)
                }
            }
            Self::Else => Action::Replace(match current_state {
                Some(State::Executing) | Some(State::SkippingUntilEndIf) => {
                    State::SkippingUntilEndIf
                }
                Some(State::SkippingUntilElseOrEndIf) => State::Executing,
                None => panic!("got an Else but not in a conditional"),
            }),
            Self::ElseIf(inner_condition) => match current_state {
                Some(State::Executing) | Some(State::SkippingUntilEndIf) => {
                    Action::Replace(State::SkippingUntilEndIf)
                }
                Some(State::SkippingUntilElseOrEndIf) => {
                    inner_condition.action(current_state, is_macro_defined, expand_macro)?
                }
                None => panic!("got an ElseIf but not in a conditional"),
            },
            Self::EndIf => Action::Pop,
        })
    }
}