aboutsummaryrefslogtreecommitdiff
path: root/src/makefile/macro.rs
blob: fb0367b9f85344b8d3b1c871569cf3544df6cd81 (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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
use std::collections::HashMap;
use std::collections::HashSet;
use std::env;
use std::fmt;
#[cfg(feature = "full")]
use std::io::BufRead;


#[cfg(feature = "full")]
use super::eval_context::DeferredEvalContext;
use super::ItemSource;
use super::{MacroScopeStack, TokenString};
use eyre::Result;
#[cfg(not(feature = "full"))]
use regex::Regex;

#[derive(Debug, Clone)]
pub struct Macro {
    pub source: ItemSource,
    pub text: TokenString,
    #[cfg(feature = "full")]
    pub eagerly_expanded: bool,
}

#[cfg(feature = "full")]
#[derive(Clone, Debug)]
pub enum ExportConfig {
    Only(HashSet<String>),
    AllBut(HashSet<String>),
}

#[cfg(feature = "full")]
impl ExportConfig {
    pub fn all_but() -> Self {
        Self::AllBut(HashSet::new())
    }

    pub fn only() -> Self {
        Self::Only(HashSet::new())
    }

    pub fn add_all<'a, I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
        match self {
            Self::Only(exported) => {
                exported.extend(iter.into_iter().map(|x| x.to_owned()));
            }
            Self::AllBut(not_exported) => {
                for added in iter {
                    not_exported.remove(added);
                }
            }
        }
    }

    pub fn remove_all<'a, I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
        match self {
            Self::Only(exported) => {
                for removed in iter {
                    exported.remove(removed);
                }
            }
            Self::AllBut(not_exported) => {
                not_exported.extend(iter.into_iter().map(|x| x.into()));
            }
        }
    }

    fn should_export(&self, x: &str) -> bool {
        match self {
            Self::Only(exported) => exported.contains(x),
            Self::AllBut(not_exported) => !not_exported.contains(x),
        }
    }
}

#[derive(Clone, Debug)]
pub struct Set {
    pub data: HashMap<String, Macro>,
    #[cfg(feature = "full")]
    pub exported: ExportConfig,
}

impl Set {
    pub fn new() -> Self {
        Self {
            data: HashMap::new(),
            #[cfg(feature = "full")]
            exported: ExportConfig::only(),
        }
    }

    pub fn add_builtins(&mut self) {
        for (k, v) in builtins() {
            self.data.insert(
                k.into(),
                Macro {
                    source: ItemSource::Builtin,
                    text: v,
                    #[cfg(feature = "full")]
                    eagerly_expanded: false,
                },
            );
        }
    }

    pub fn add_env(&mut self) {
        for (k, v) in env::vars() {
            if k != "MAKEFLAGS" && k != "SHELL" {
                self.data.insert(
                    k,
                    Macro {
                        source: ItemSource::Environment,
                        text: TokenString::text(v),
                        #[cfg(feature = "full")]
                        eagerly_expanded: false,
                    },
                );
            }
        }
    }

    pub fn get(&self, name: &str) -> Option<&Macro> {
        self.data.get(name)
    }

    pub fn set(&mut self, name: String, r#macro: Macro) {
        self.data.insert(name, r#macro);
    }

    #[cfg(feature = "full")]
    pub fn is_defined(&self, name: &str) -> bool {
        self.get(name).map_or(false, |x| !x.text.is_empty())
    }

    // `remove` is fine, but I think for "remove-and-return" `pop` is better
    pub fn pop(&mut self, name: &str) -> Option<Macro> {
        // TODO figure out a better way to handle inheritance
        self.data.remove(name)
    }

    pub fn extend(
        &mut self,
        other: HashMap<String, Macro>,
        #[cfg(feature = "full")] other_exports: ExportConfig,
    ) {
        #[cfg(feature = "full")]
        match (&mut self.exported, other_exports) {
            (ExportConfig::Only(se), ExportConfig::Only(oe)) => {
                se.extend(oe);
            }
            (ExportConfig::AllBut(sne), ExportConfig::AllBut(one)) => {
                sne.extend(one);
            }
            (ExportConfig::Only(se), ExportConfig::AllBut(one)) => {
                se.extend(other.keys().filter(|name| !one.contains(*name)).cloned());
            }
            (ExportConfig::AllBut(sne), ExportConfig::Only(oe)) => {
                sne.extend(other.keys().filter(|name| !oe.contains(*name)).cloned());
            }
        }
        self.data.extend(other);
    }

    #[cfg(feature = "full")]
    pub fn resolve_exports<R: BufRead>(
        &self,
        mut eval_context: Option<&mut DeferredEvalContext<R>>,
    ) -> Result<Vec<(&str, String)>> {
        let own_exports = self
            .data
            .iter()
            .filter(|(name, _)| self.exported.should_export(name))
            .map(|(name, value)| {
                MacroScopeStack::from_scope(self)
                    .expand(&value.text, eval_context.as_deref_mut())
                    .map(|text| (name.as_ref(), text))
            })
            .collect::<Result<Vec<_>>>()?;
        Ok(own_exports)
    }
}

impl fmt::Display for Set {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let pieces = self
            .data
            .iter()
            .map(|(k, x)| format!("{}={}", k, &x.text))
            .collect::<Vec<_>>();
        write!(f, "{}", pieces.join("\n"))
    }
}

impl Default for Set {
    fn default() -> Self {
        Self::new()
    }
}

fn builtins() -> Vec<(&'static str, TokenString)> {
    // Fuck it, might as well.
    macro_rules! handle {
        ($value:ident) => {
            stringify!($value).parse().unwrap()
        };
        ($value:literal) => {
            $value.parse().unwrap()
        };
        ($value:expr) => {
            $value
        };
    }
    macro_rules! make {
        ($($name:ident=$value:tt)+) => {vec![$(
            (stringify!($name), handle!($value))
        ),+]};
    }

    make![
        AR=ar
        YACC=yacc
        YFLAGS=""
        LEX=lex
        LFLAGS=""
        LDFLAGS=""

        AS=as
        CC=cc
        CXX="g++"
        CPP="$(CC) -E"
        FC=f77
        PC=pc
        CO=co
        GET=get
        LINT=lint
        MAKEINFO=makeinfo
        TEX=tex
        TEXI2DVI=texi2dvi
        WEAVE=weave
        CWEAVE=cweave
        TANGLE=tangle
        CTANGLE=ctangle
        RM="rm -f"

        ARFLAGS="rv"
        CFLAGS=""
        FFLAGS=""
    ]
}

#[cfg(test)]
mod test {
    use super::*;
    #[cfg(feature = "full")]
    use crate::makefile::functions::NO_EVAL;

    type R = Result<()>;

    #[test]
    fn subst() -> R {
        let mut macros = Set::new();
        macros.set(
            "oof".to_owned(),
            Macro {
                source: ItemSource::Builtin,
                text: TokenString::text("bruh; swag; yeet;"),
                #[cfg(feature = "full")]
                eagerly_expanded: false,
            },
        );
        assert_eq!(
            MacroScopeStack::from_scope(&macros).expand(
                &"$(oof:;=?)".parse()?,
                #[cfg(feature = "full")]
                NO_EVAL
            )?,
            "bruh? swag? yeet?"
        );
        Ok(())
    }

    #[test]
    #[cfg(feature = "full")]
    fn hell_subst() -> R {
        let mut macros = Set::new();
        macros.set(
            "m".to_owned(),
            Macro {
                source: ItemSource::FunctionCall,
                text: TokenString::text("conf"),
                eagerly_expanded: false,
            },
        );
        assert_eq!(
            MacroScopeStack::from_scope(&macros).expand(&"$(m:%=%-objs)".parse()?, NO_EVAL)?,
            "conf-objs"
        );
        Ok(())
    }
}