aboutsummaryrefslogtreecommitdiff
path: root/src/makefile/mod.rs
blob: 5c38ab32b7b6138c5bb4b35a6b8dc5c3b47475b4 (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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
use std::cell::{Cell, RefCell};
use std::env;
use std::fmt;
use std::path::{Path, PathBuf};
use std::rc::Rc;

use eyre::{bail, eyre, Result, WrapErr};

use command_line::CommandLine;
use inference_rules::InferenceRule;
use input::FinishedMakefileReader;
pub use input::MakefileReader;
use r#macro::{Macro, Set as MacroSet};
use target::{DynamicTargetSet, Target};
use token::TokenString;

use crate::args::Args;

mod command_line;
#[cfg(feature = "full")]
mod conditional;
#[cfg(feature = "full")]
mod functions;
mod inference_rules;
mod input;
mod r#macro;
mod pattern;
mod target;
mod token;

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum ItemSource {
    File { name: String, line: usize },
    CommandLineOrMakeflags,
    Environment,
    Builtin,
    FunctionCall,
}

pub struct Makefile<'a> {
    inference_rules: Vec<InferenceRule>,
    builtin_inference_rules: Vec<InferenceRule>,
    pub macros: MacroSet<'static, 'static>,
    targets: RefCell<DynamicTargetSet>,
    pub first_non_special_target: Option<String>,
    args: &'a Args,
    // TODO borrow warnings from Python version
}

impl<'a> Makefile<'a> {
    pub fn new(args: &'a Args) -> Self {
        let mut inference_rules = vec![];
        let mut macros = MacroSet::new();
        let mut targets = DynamicTargetSet::default();
        let first_non_special_target = None;

        macros.set(
            "MAKE".to_owned(),
            Macro {
                source: ItemSource::Builtin,
                text: std::env::current_exe().map_or_else(
                    |_| TokenString::text("makers"),
                    |x| TokenString::text(x.to_string_lossy()),
                ),
                #[cfg(feature = "full")]
                eagerly_expanded: false,
            },
        );
        if !args.no_builtin_rules {
            inference_rules.extend(builtin_inference_rules());
            macros.add_builtins();
            for target in builtin_targets() {
                targets.put(target);
            }
        }

        macros.add_env();

        for r#macro in args.macros() {
            if let [name, value] = *r#macro.splitn(2, '=').collect::<Vec<_>>() {
                macros.set(
                    name.into(),
                    Macro {
                        source: ItemSource::CommandLineOrMakeflags,
                        text: TokenString::text(value),
                        #[cfg(feature = "full")]
                        eagerly_expanded: false,
                    },
                );
            }
        }

        #[cfg(feature = "full")]
        {
            let make_cmd_goals = args.targets().collect::<Vec<_>>();
            macros.set(
                "MAKECMDGOALS".to_owned(),
                Macro {
                    source: ItemSource::Builtin,
                    text: TokenString::text(make_cmd_goals.join(" ")),
                    #[cfg(feature = "full")]
                    eagerly_expanded: false,
                },
            );

            if let Ok(curdir) = env::current_dir() {
                macros.set(
                    "CURDIR".to_owned(),
                    Macro {
                        source: ItemSource::Builtin,
                        text: TokenString::text(curdir.to_string_lossy()),
                        #[cfg(feature = "full")]
                        eagerly_expanded: false,
                    },
                );
            }
        }

        Makefile {
            inference_rules: vec![],
            builtin_inference_rules: inference_rules,
            macros,
            targets: RefCell::new(targets),
            first_non_special_target,
            args,
        }
    }

    pub fn extend(&mut self, new: FinishedMakefileReader) -> Result<()> {
        self.inference_rules.extend(new.inference_rules);
        self.macros.extend(
            new.macros,
            #[cfg(feature = "full")]
            new.macro_exports,
        );
        for (_, target) in new.targets {
            self.targets.borrow_mut().put(target);
        }
        if self.first_non_special_target.is_none() {
            self.first_non_special_target = new.first_non_special_target;
        }
        for failed_include in new.failed_includes {
            // try rebuilding
            self.update_target(&failed_include).wrap_err_with(|| {
                format!("while building missing included file {}", &failed_include)
            })?;
            let macros = self.macros.with_overlay();
            let file = MakefileReader::read_file(self.args, macros, failed_include)?.finish();
            self.extend(file)?;
        }
        Ok(())
    }

    fn special_target_has_prereq(&self, target: &str, name: &str) -> bool {
        let targets = self.targets.borrow();
        match targets.get(target) {
            Some(target) => {
                let target = target.borrow();
                target.prerequisites.is_empty() || target.prerequisites.iter().any(|e| e == name)
            }
            None => false,
        }
    }

    fn infer_target(
        &self,
        name: &str,
        banned_rules: Vec<&InferenceRule>,
        banned_names: Vec<&str>,
    ) -> Result<()> {
        if banned_names.contains(&name) {
            bail!("no infinite recursion allowed");
        }
        log::trace!("inferring {}, stack = {:?}", name, banned_names);
        let mut new_target = None;

        let follow_gnu = cfg!(feature = "full");

        let vpath_options = match self.macros.get("VPATH") {
            Some(Macro { text, .. }) if follow_gnu => {
                let vpath = self.expand_macros(text, None)?;
                env::split_paths(&vpath).collect()
            }
            _ => vec![],
        };
        // When no target rule is found to update a target, the inference rules shall
        // be checked. The suffix of the target to be built is compared to the list of
        // suffixes specified by the .SUFFIXES special targets. If the .s1 suffix is
        // found in .SUFFIXES...
        // TODO bring back .SUFFIXES for suffix-based rules
        // the inference rules shall be searched in the order defined...
        // TODO implement GNUish shortest-stem-first matching
        let inference_rule_candidates = self
            .inference_rules
            .iter()
            .chain(self.builtin_inference_rules.iter())
            .filter(|rule| !banned_rules.contains(rule))
            .filter(|rule| rule.matches(name).unwrap_or(false));
        for rule in inference_rule_candidates {
            log::trace!(
                "{} considering rule to build {:?} from {:?}",
                name,
                &rule.products,
                &rule.prerequisites
            );
            // whose prerequisite file ($*.s2) exists.
            let prereq_paths = rule
                .prereqs(name)?
                .map(|prereq_path_name| {
                    if name == prereq_path_name || banned_names.contains(&&*prereq_path_name) {
                        // we can't build this based on itself! fuck outta here
                        return None;
                    }
                    if self.targets.borrow().has(&prereq_path_name) {
                        return Some(prereq_path_name);
                    }
                    let prereq_path = PathBuf::from(&prereq_path_name);
                    let prereq_vpath_options = if prereq_path.is_absolute() {
                        None
                    } else {
                        Some(vpath_options.iter().map(|vpath| vpath.join(&prereq_path)))
                    }
                    .into_iter()
                    .flatten();
                    std::iter::once(prereq_path.clone())
                        .chain(prereq_vpath_options)
                        .find(|prereq| prereq.exists())
                        .map(|path| path.to_string_lossy().to_string())
                        .or_else(|| {
                            let mut banned_rules = banned_rules.clone();
                            banned_rules.push(rule);
                            let mut banned_names = banned_names.clone();
                            banned_names.push(name);
                            self.infer_target(&prereq_path_name, banned_rules, banned_names)
                                .ok()
                                .and_then(|_| {
                                    if self.targets.borrow().has(&prereq_path_name) {
                                        Some(prereq_path_name)
                                    } else {
                                        None
                                    }
                                })
                        })
                })
                .collect::<Option<Vec<String>>>();
            if let Some(prereqs) = prereq_paths {
                log::trace!("oh {} is a {}", name, rule);
                new_target = Some(Target {
                    name: name.into(),
                    prerequisites: prereqs,
                    commands: rule.commands.clone(),
                    stem: rule
                        .first_match(name)?
                        .and_then(|x| x.get(1).map(|x| x.as_str().to_owned())),
                    already_updated: Cell::new(false),
                });
                break;
            }
        }

        if let Some(new_target) = new_target {
            self.targets.borrow_mut().put(new_target);
        }

        Ok(())
    }

    pub fn get_target(&self, name: &str) -> Result<Rc<RefCell<Target>>> {
        // TODO implement .POSIX
        let follow_gnu = cfg!(feature = "full");

        let exists_but_infer_anyway = if follow_gnu {
            self.targets
                .borrow()
                .get(name)
                .map_or(false, |target| target.borrow().commands.is_empty())
        } else {
            false
        };
        if !self.targets.borrow().has(name) || exists_but_infer_anyway {
            log::trace!("trying to infer for {}", name);
            self.infer_target(name, vec![], vec![])?;
        }

        let mut new_target = None;
        let targets = self.targets.borrow();
        if !targets.has(name) {
            // well, inference didn't work. is there a default?
            if let Some(default) = targets.get(".DEFAULT") {
                let commands = default.borrow().commands.clone();
                new_target = Some(Target {
                    name: name.into(),
                    prerequisites: vec![],
                    commands,
                    stem: None,
                    already_updated: Cell::new(false),
                });
            } else {
                // if it already exists, it counts as up-to-date
                if Path::new(name).exists() {
                    new_target = Some(Target {
                        name: name.into(),
                        prerequisites: vec![],
                        commands: vec![],
                        stem: None,
                        already_updated: Cell::new(true),
                    });
                }
            }
        }

        drop(targets);
        if let Some(new_target) = new_target {
            self.targets.borrow_mut().put(new_target);
        }

        let targets = self.targets.borrow();
        Ok(targets
            .get(name)
            .ok_or_else(|| eyre!("Target {:?} not found!", name))?)
    }

    pub fn update_target(&self, name: &str) -> Result<()> {
        self.get_target(name)?.borrow().update(self)
    }

    fn expand_macros(&self, text: &TokenString, target: Option<&Target>) -> Result<String> {
        let target = target.cloned();
        let lookup_internal = move |macro_name: &str| {
            let target = target
                .as_ref()
                .ok_or_else(|| eyre!("internal macro but no current target!"))?;
            let macro_pieces = if macro_name.starts_with('@') {
                // The $@ shall evaluate to the full target name of the
                // current target.
                vec![target.name.clone()]
            } else if macro_name.starts_with('?') {
                // The $? macro shall evaluate to the list of prerequisites
                // that are newer than the current target.
                target
                    .prerequisites
                    .iter()
                    .filter(|prereq| {
                        self.get_target(prereq)
                            .ok()
                            .and_then(|prereq| prereq.borrow().newer_than(target))
                            .unwrap_or(false)
                    })
                    .cloned()
                    .collect()
            } else if macro_name.starts_with('<') {
                // In an inference rule, the $< macro shall evaluate to the
                // filename whose existence allowed the inference rule to be
                // chosen for the target. In the .DEFAULT rule, the $< macro
                // shall evaluate to the current target name.
                // TODO make that actually be the case (rn exists_but_inferring_anyway might fuck that up)
                vec![target.prerequisites.get(0).cloned().unwrap_or_default()]
            } else if macro_name.starts_with('*') {
                // The $* macro shall evaluate to the current target name with
                // its suffix deleted. (GNUism: the match stem)
                vec![target.stem.as_ref().unwrap_or(&target.name).to_owned()]
            } else if macro_name.starts_with('^') {
                target.prerequisites.clone()
            } else {
                unreachable!()
            };

            let macro_pieces = if macro_name.ends_with('D') {
                macro_pieces
                    .into_iter()
                    .map(|x| {
                        Path::new(&x)
                            .parent()
                            .ok_or_else(|| eyre!("no parent"))
                            .map(|x| x.to_string_lossy().into())
                    })
                    .collect::<Result<_, _>>()?
            } else if macro_name.ends_with('F') {
                macro_pieces
                    .into_iter()
                    .map(|x| {
                        Path::new(&x)
                            .file_name()
                            .ok_or_else(|| eyre!("no filename"))
                            .map(|x| x.to_string_lossy().into())
                    })
                    .collect::<Result<_, _>>()?
            } else {
                macro_pieces
            };

            Ok(macro_pieces.join(" "))
        };

        self.macros.with_lookup(&lookup_internal).expand(text)
    }
}

impl fmt::Display for Makefile<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let header = |f: &mut fmt::Formatter, t: &str| {
            writeln!(f, "{}\n{:=^width$}", t, "", width = t.len())
        };
        header(f, "Inference Rules")?;
        for rule in self
            .inference_rules
            .iter()
            .chain(self.builtin_inference_rules.iter())
        {
            writeln!(f, "{}", rule)?;
        }
        writeln!(f)?;

        header(f, "Macros")?;
        writeln!(f, "{}", &self.macros)?;
        writeln!(f)?;

        header(f, "Targets")?;
        writeln!(f, "{}", &self.targets.borrow())?;

        Ok(())
    }
}

fn builtin_inference_rules() -> Vec<InferenceRule> {
    // This is a terrible idea.
    macro_rules! prepend_dot {
        ($x:tt) => {
            concat!(".", stringify!($x))
        };
        () => {
            ""
        };
    }

    macro_rules! make {
        {$(.$first:tt$(.$second:tt)?:
            $($cmd:literal)+)+} => {
            vec![$(
                InferenceRule::new_suffix(
                    ItemSource::Builtin,
                    prepend_dot!($($second)?).into(),
                    concat!(".", stringify!($first)).into(),
                    vec![$(CommandLine::from($cmd.parse().unwrap())),+],
                )
            ),+]
        };
    }

    make! {
        .c:
            "$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $<"
        .f:
            "$(FC) $(FFLAGS) $(LDFLAGS) -o $@ $<"
        .sh:
            "cp $< $@"
            "chmod a+x $@"

        .c.o:
            "$(CC) $(CFLAGS) -c $<"
        .f.o:
            "$(FC) $(FFLAGS) -c $<"
        .y.o:
            "$(YACC) $(YFLAGS) $<"
            "$(CC) $(CFLAGS) -c y.tab.c"
            "rm -f y.tab.c"
            "mv y.tab.o $@"
        .l.o:
            "$(LEX) $(LFLAGS) $<"
            "$(CC) $(CFLAGS) -c lex.yy.c"
            "rm -f lex.yy.c"
            "mv lex.yy.o $@"
        .y.c:
            "$(YACC) $(YFLAGS) $<"
            "mv y.tab.c $@"
        .l.c:
            "$(LEX) $(LFLAGS) $<"
            "mv lex.yy.c $@"
        .c.a:
            "$(CC) -c $(CFLAGS) $<"
            "$(AR) $(ARFLAGS) $@ $*.o"
            "rm -f $*.o"
        .f.a:
            "$(FC) -c $(FFLAGS) $<"
            "$(AR) $(ARFLAGS) $@ $*.o"
            "rm -f $*.o"
    }
}
fn builtin_targets() -> Vec<Target> {
    // even i'm not going to do that just for this
    vec![Target {
        name: ".SUFFIXES".into(),
        prerequisites: vec![".o", ".c", ".y", ".l", ".a", ".sh", ".f"]
            .into_iter()
            .map(String::from)
            .collect(),
        commands: vec![],
        stem: None,
        already_updated: Cell::new(false),
    }]
}

#[cfg(test)]
mod test {
    use super::*;

    type R = Result<()>;

    #[cfg(feature = "full")]
    #[test]
    fn stem() -> R {
        let args = Args::empty();
        let rule = InferenceRule {
            source: ItemSource::Builtin,
            products: vec!["this-is-a-%-case".to_owned()],
            prerequisites: vec![],
            commands: vec![],
        };
        let file = Makefile {
            inference_rules: vec![rule],
            builtin_inference_rules: vec![],
            macros: MacroSet::new(),
            targets: Default::default(),
            first_non_special_target: None,
            args: &args,
        };

        let target = file.get_target("this-is-a-test-case")?;
        assert_eq!(target.borrow().stem, Some("test".to_owned()));
        Ok(())
    }
}