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
|
use std::cell::RefCell;
use std::env;
use std::process::{Command, Stdio};
use std::rc::Rc;
use eyre::{bail, Result};
use super::pattern::r#match;
use super::r#macro::{Set as MacroSet, Source as MacroSource};
use super::token::TokenString;
pub fn expand_call(
name: &str,
args: &[TokenString],
macros: &MacroSet,
to_eval: Option<Rc<RefCell<Vec<String>>>>,
) -> Result<String> {
match name {
"filter" => {
assert_eq!(args.len(), 2);
text::filter(macros, &args[0], &args[1])
}
"filter-out" => {
assert_eq!(args.len(), 2);
text::filter_out(macros, &args[0], &args[1])
}
"sort" => {
assert_eq!(args.len(), 1);
text::sort(macros, &args[0])
}
"notdir" => {
assert_eq!(args.len(), 1);
file_name::notdir(macros, &args[0])
}
"basename" => {
assert_eq!(args.len(), 1);
file_name::basename(macros, &args[0])
}
"addprefix" => {
assert_eq!(args.len(), 2);
file_name::addprefix(macros, &args[0], &args[1])
}
"wildcard" => {
assert_eq!(args.len(), 1);
file_name::wildcard(macros, &args[0])
}
"if" => {
assert!(args.len() == 2 || args.len() == 3);
conditional::r#if(macros, &args[0], &args[1], args.get(2))
}
// foreach
"foreach" => {
assert_eq!(args.len(), 3);
foreach(macros, &args[0], &args[1], &args[2])
}
// call
"call" => {
assert!(!args.is_empty());
call(macros, args.iter())
}
// eval
"eval" => {
assert_eq!(args.len(), 1);
let should_eval = eval(macros, &args[0])?;
if let Some(to_eval) = to_eval {
to_eval.borrow_mut().push(should_eval);
} else {
bail!("tried to eval something but no eval back-channel was available");
}
Ok(String::new())
}
"origin" => {
assert_eq!(args.len(), 1);
origin(macros, &args[0])
}
// shell
"shell" => {
assert_eq!(args.len(), 1);
shell(macros, &args[0])
}
// fallback
_ => bail!("function not implemented: {}", name),
}
}
// Text Functions
mod text {
use super::*;
pub fn filter(macros: &MacroSet, patterns: &TokenString, text: &TokenString) -> Result<String> {
let patterns = macros.expand(patterns)?;
let patterns = patterns.split_whitespace().collect::<Vec<_>>();
let text = macros.expand(text)?;
let text = text.split_whitespace();
let mut result_pieces = vec![];
for word in text {
if patterns
.iter()
.any(|pattern| r#match(pattern, word).map_or(false, |x| x.is_some()))
{
result_pieces.push(word);
}
}
Ok(result_pieces.join(" "))
}
pub fn filter_out(
macros: &MacroSet,
patterns: &TokenString,
text: &TokenString,
) -> Result<String> {
let patterns = macros.expand(patterns)?;
let patterns = patterns.split_whitespace().collect::<Vec<_>>();
let text = macros.expand(text)?;
let text = text.split_whitespace();
let mut result_pieces = vec![];
for word in text {
if patterns
.iter()
.all(|pattern| r#match(pattern, word).map_or(false, |x| x.is_none()))
{
result_pieces.push(word);
}
}
Ok(result_pieces.join(" "))
}
pub fn sort(macros: &MacroSet, words: &TokenString) -> Result<String> {
let words = macros.expand(words)?;
let mut words = words.split_whitespace().collect::<Vec<_>>();
words.sort_unstable();
words.dedup();
Ok(words.join(" "))
}
}
// File Name Functions
mod file_name {
use std::env;
use std::ffi::OsStr;
use std::path::Path;
use eyre::WrapErr;
use super::*;
pub fn notdir(macros: &MacroSet, words: &TokenString) -> Result<String> {
let words = macros.expand(words)?;
let words = words
.split_whitespace()
.map(|word| {
Path::new(word)
.file_name()
.and_then(OsStr::to_str)
.unwrap_or("")
})
.collect::<Vec<_>>();
Ok(words.join(" "))
}
pub fn basename(macros: &MacroSet, words: &TokenString) -> Result<String> {
let words = macros.expand(words)?;
let words = words
.split_whitespace()
.map(|word| {
Path::new(word)
.with_extension("")
.to_str()
.map_or_else(String::new, ToString::to_string)
})
.collect::<Vec<_>>();
Ok(words.join(" "))
}
pub fn addprefix(
macros: &MacroSet,
prefix: &TokenString,
targets: &TokenString,
) -> Result<String> {
let prefix = macros.expand(prefix)?;
let targets = macros.expand(targets)?;
let results = targets
.split_whitespace()
.map(|t| format!("{}{}", prefix, t))
.collect::<Vec<_>>();
Ok(results.join(" "))
}
pub fn wildcard(macros: &MacroSet, pattern: &TokenString) -> Result<String> {
let pattern = macros.expand(pattern)?;
let home_dir = env::var("HOME")
.ok()
.or_else(|| dirs::home_dir().and_then(|p| p.to_str().map(String::from)));
let pattern = if let Some(home_dir) = home_dir {
pattern.replace('~', &home_dir)
} else {
pattern
};
let results = glob::glob(&pattern)
.context("invalid glob pattern!")?
.filter_map(|path| {
path.ok()
.map(|x| x.to_str().map(ToString::to_string).unwrap_or_default())
})
.collect::<Vec<_>>();
Ok(results.join(" "))
}
}
// Functions for Conditionals
mod conditional {
use super::*;
pub fn r#if(
macros: &MacroSet,
condition: &TokenString,
if_true: &TokenString,
if_false: Option<&TokenString>,
) -> Result<String> {
let mut condition = condition.clone();
condition.trim_start();
condition.trim_end();
let condition = macros.expand(&condition)?;
if condition.is_empty() {
if let Some(if_false) = if_false {
macros.expand(if_false)
} else {
Ok(String::new())
}
} else {
macros.expand(if_true)
}
}
}
pub fn foreach(
macros: &MacroSet,
var: &TokenString,
list: &TokenString,
text: &TokenString,
) -> Result<String> {
let var = macros.expand(var)?;
let list = macros.expand(list)?;
let words = list.split_whitespace();
let mut macros = macros.with_overlay();
let results = words
.map(|word| {
macros.set(var.clone(), MacroSource::File, TokenString::text(word));
macros.expand(text)
})
.collect::<Result<Vec<_>, _>>()?;
Ok(results.join(" "))
}
pub fn call<'a>(macros: &MacroSet, args: impl Iterator<Item = &'a TokenString>) -> Result<String> {
let args = args
.map(|arg| macros.expand(arg))
.collect::<Result<Vec<_>, _>>()?;
let function = args[0].clone();
// TODO if function is a builtin, call the builtin instead
let mut macros = macros.with_overlay();
for (i, x) in args.into_iter().enumerate() {
macros.set(i.to_string(), MacroSource::File, TokenString::text(x));
}
macros.expand(&TokenString::r#macro(function))
}
// TODO consider bringing eval logic in here since we put the Vec in MacroSet IIRC
pub fn eval(macros: &MacroSet, arg: &TokenString) -> Result<String> {
macros.expand(arg)
}
pub fn origin(macros: &MacroSet, variable: &TokenString) -> Result<String> {
let variable = macros.expand(variable)?;
Ok(macros.origin(&variable).to_owned())
}
pub fn shell(macros: &MacroSet, command: &TokenString) -> Result<String> {
// TODO bring this in from command_line
let command = macros.expand(command)?;
let (program, args) = if cfg!(windows) {
let cmd = env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".into());
let args = vec!["/c", &command];
(cmd, args)
} else {
let sh = env::var("SHELL").unwrap_or_else(|_| "/bin/sh".into());
let args = vec!["-e", "-c", &command];
(sh, args)
};
let result = Command::new(program)
.args(args)
.stderr(Stdio::inherit())
.output()?;
let _status = result.status;
// TODO set .SHELLSTATUS
Ok(String::from_utf8(result.stdout)?
.replace("\r\n", "\n")
.trim_end_matches('\n')
.replace("\n", " "))
}
#[cfg(test)]
mod test {
use super::*;
use crate::makefile::r#macro::{Set as MacroSet, Source as MacroSource};
type R = Result<()>;
fn call(name: &str, args: &[TokenString], macros: &MacroSet) -> Result<String> {
super::expand_call(name, args, macros, None)
}
macro_rules! call {
($func:literal $($arg:literal),+) => {
call($func, &[$(TokenString::text($arg)),+], &MacroSet::new())?
};
($func:ident $($arg:literal),+) => {
call(stringify!($func), &[$(TokenString::text($arg)),+], &MacroSet::new())?
};
}
#[test]
fn filter() -> R {
let result = call!(filter "word", "this contains a word inside it");
assert_eq!(result, "word");
let result = call!(filter "%.c %.s", "foo.c bar.c baz.s ugh.h");
assert_eq!(result, "foo.c bar.c baz.s");
Ok(())
}
#[test]
fn filter_out() -> R {
let result = call!("filter-out" "main1.o main2.o", "main1.o foo.o main2.o bar.o");
assert_eq!(result, "foo.o bar.o");
Ok(())
}
#[test]
fn sort() -> R {
let result = call!(sort "foo bar lose foo");
assert_eq!(result, "bar foo lose");
Ok(())
}
#[test]
fn notdir() -> R {
let result = call!(notdir "src/foo.c hacks");
assert_eq!(result, "foo.c hacks");
Ok(())
}
#[test]
fn basename() -> R {
let result = call!(basename "src/foo.c src-1.0/bar hacks");
assert_eq!(result, "src/foo src-1.0/bar hacks");
Ok(())
}
#[test]
fn addprefix() -> R {
let result = call!(addprefix "src/", "foo bar");
assert_eq!(result, "src/foo src/bar");
Ok(())
}
#[test]
fn wildcard() -> R {
use std::env::{set_current_dir, set_var};
use std::fs::write;
use std::path::MAIN_SEPARATOR;
let tempdir = tempfile::tempdir()?;
write(tempdir.path().join("foo.c"), "")?;
write(tempdir.path().join("bar.h"), "")?;
write(tempdir.path().join("baz.txt"), "")?;
write(tempdir.path().join("acab.c"), "ACAB")?;
write(tempdir.path().join("based.txt"), "☭")?;
set_current_dir(tempdir.path())?;
set_var("HOME", tempdir.path());
let sort = |x: String| call("sort", &[TokenString::text(&x)], &MacroSet::new());
assert_eq!(sort(call!(wildcard "*.c"))?, "acab.c foo.c");
assert_eq!(
sort(call!(wildcard "~/ba?.*"))?,
format!(
"{0}{1}bar.h {0}{1}baz.txt",
tempdir.path().display(),
MAIN_SEPARATOR
)
);
Ok(())
}
#[test]
fn foreach() -> R {
let mut macros = MacroSet::new();
macros.set(
"test".to_owned(),
MacroSource::File,
"worked for $(item).".parse()?,
);
assert_eq!(
call(
"foreach",
&[
TokenString::text("item"),
TokenString::text("a b c d"),
TokenString::r#macro("test")
],
¯os,
)?,
"worked for a. worked for b. worked for c. worked for d."
);
Ok(())
}
#[test]
fn call_test() -> R {
let mut macros = MacroSet::new();
macros.set(
"reverse".to_owned(),
MacroSource::File,
"$(2) $(1)".parse()?,
);
assert_eq!(
call(
"call",
&[
TokenString::text("reverse"),
TokenString::text("a"),
TokenString::text("b")
],
¯os,
)?,
"b a"
);
Ok(())
}
#[test]
fn shell() -> R {
let result = call!(shell "echo hi");
assert_eq!(result, "hi");
Ok(())
}
}
|