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
|
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::env;
use std::fmt;
use std::path::Path;
use std::rc::Rc;
use eyre::{eyre, Result};
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;
#[cfg(feature = "full")]
mod pattern;
mod target;
mod token;
use inference_rules::InferenceRule;
pub use input::MakefileReader;
use r#macro::Set as MacroSet;
use target::Target;
use token::TokenString;
pub struct Makefile<'a> {
inference_rules: Vec<InferenceRule>,
macros: MacroSet<'static, 'static>,
targets: RefCell<HashMap<String, Rc<RefCell<Target>>>>,
pub first_non_special_target: Option<String>,
args: &'a Args,
// TODO borrow warnings from Python version
}
impl<'a> Makefile<'a> {
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,
}
}
pub fn get_target(&self, name: &str) -> Result<Rc<RefCell<Target>>> {
// TODO implement .POSIX
let follow_gnu = true;
let vpath_options = match self.macros.get("VPATH") {
Some((_, vpath)) if follow_gnu => {
let vpath = self.expand_macros(vpath, None)?;
env::split_paths(&vpath).collect()
}
_ => vec![],
};
let targets = self.targets.borrow();
let mut new_target = None;
let exists_but_infer_anyway = if follow_gnu {
targets
.get(name)
.map_or(false, |target| target.borrow().commands.is_empty())
} else {
false
};
if !targets.contains_key(name) || exists_but_infer_anyway {
// When no target rule is found to update a target, the inference rules shall
// be checked. The suffix of the target to be built...
let suffix = Path::new(name)
.extension()
.map_or_else(String::new, |ext| format!(".{}", ext.to_string_lossy()));
// is compared to the list of suffixes specified by the .SUFFIXES special
// targets. If the .s1 suffix is found in .SUFFIXES...
if self.special_target_has_prereq(".SUFFIXES", &suffix) || suffix.is_empty() {
// the inference rules shall be searched in the order defined...
'rules: for rule in self
.inference_rules
.iter()
// for the first .s2.s1 rule...
.filter(|rule| rule.product == suffix)
{
// whose prerequisite file ($*.s2) exists.
let prereq_path =
Path::new(name).with_extension(rule.prereq.trim_start_matches('.'));
if let Some(prereq) = std::iter::once(prereq_path.clone())
.chain(
if prereq_path.is_absolute() {
None
} else {
Some(vpath_options.iter().map(|vpath| vpath.join(&prereq_path)))
}
.into_iter()
.flatten(),
)
.find(|prereq| prereq.exists())
{
new_target = Some(Target {
name: name.into(),
prerequisites: vec![prereq.to_string_lossy().into()],
commands: rule.commands.clone(),
already_updated: Cell::new(false),
});
break 'rules;
}
}
}
}
if !targets.contains_key(name) && new_target.is_none() {
// 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,
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![],
already_updated: Cell::new(true),
});
}
}
}
drop(targets);
if let Some(new_target) = new_target {
self.targets
.borrow_mut()
.insert(new_target.name.clone(), Rc::new(RefCell::new(new_target)));
}
let targets = self.targets.borrow();
Ok(Rc::clone(
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 |name: &str| {
let target = target
.as_ref()
.ok_or_else(|| eyre!("internal macro but no current target!"))?;
let macro_pieces = if name.starts_with('@') {
// The $@ shall evaluate to the full target name of the
// current target.
vec![target.name.clone()]
} else if 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 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.
target.prerequisites.clone()
} else if name.starts_with('*') {
// The $* macro shall evaluate to the current target name with
// its suffix deleted.
vec![Path::new(name).with_extension("").to_string_lossy().into()]
} else {
unreachable!()
};
let macro_pieces = if 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 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 {
writeln!(f, "{}", rule)?;
}
writeln!(f)?;
header(f, "Macros")?;
writeln!(f, "{}", &self.macros)?;
writeln!(f)?;
header(f, "Targets")?;
for target in self.targets.borrow().values() {
writeln!(f, "{}", target.borrow())?;
}
Ok(())
}
}
|