Make join accept two or more arguments (#1000)

This commit is contained in:
Casey Rodarmor 2021-10-14 17:00:58 -07:00 committed by GitHub
parent 6786bb0953
commit 58a196f434
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 219 additions and 25 deletions

View File

@ -907,7 +907,7 @@ These functions can fail, for example if a path does not have an extension, whic
===== Infallible ===== Infallible
- `join(a, b)` - Join path `a` with path `b`. `join("foo/bar", "baz")` is `foo/bar/baz`. - `join(a, b)` - Join path `a` with path `b`. `join("foo/bar", "baz")` is `foo/bar/baz`. Accepts two or more arguments.
- `clean(path)` - Simplify `path` by removing extra path separators, intermediate `.` components, and `..` where possible. `clean("foo//bar")` is `foo/bar`, `clean("foo/..")` is `.`, `clean("foo/./bar")` is `foo/bar`. - `clean(path)` - Simplify `path` by removing extra path separators, intermediate `.` components, and `..` where possible. `clean("foo//bar")` is `foo/bar`, `clean("foo/..")` is `.`, `clean("foo/./bar")` is `foo/bar`.
=== Command Evaluation Using Backticks === Command Evaluation Using Backticks

View File

@ -82,6 +82,17 @@ impl<'src: 'run, 'run> AssignmentResolver<'src, 'run> {
self.resolve_expression(a)?; self.resolve_expression(a)?;
self.resolve_expression(b) self.resolve_expression(b)
} }
Thunk::BinaryPlus {
args: ([a, b], rest),
..
} => {
self.resolve_expression(a)?;
self.resolve_expression(b)?;
for arg in rest {
self.resolve_expression(arg)?;
}
Ok(())
}
Thunk::Ternary { Thunk::Ternary {
args: [a, b, c], .. args: [a, b, c], ..
} => { } => {

View File

@ -19,17 +19,19 @@ pub(crate) use std::{
}; };
// dependencies // dependencies
pub(crate) use camino::Utf8Path; pub(crate) use ::{
pub(crate) use derivative::Derivative; camino::Utf8Path,
pub(crate) use edit_distance::edit_distance; derivative::Derivative,
pub(crate) use lexiclean::Lexiclean; edit_distance::edit_distance,
pub(crate) use libc::EXIT_FAILURE; lexiclean::Lexiclean,
pub(crate) use log::{info, warn}; libc::EXIT_FAILURE,
pub(crate) use regex::Regex; log::{info, warn},
pub(crate) use snafu::{ResultExt, Snafu}; regex::Regex,
pub(crate) use strum::{Display, EnumString, IntoStaticStr}; snafu::{ResultExt, Snafu},
pub(crate) use typed_arena::Arena; strum::{Display, EnumString, IntoStaticStr},
pub(crate) use unicode_width::{UnicodeWidthChar, UnicodeWidthStr}; typed_arena::Arena,
unicode_width::{UnicodeWidthChar, UnicodeWidthStr},
};
// modules // modules
pub(crate) use crate::{completions, config, config_error, setting}; pub(crate) use crate::{completions, config, config_error, setting};

View File

@ -137,7 +137,7 @@ impl Display for CompileError<'_> {
function, function,
found, found,
Count("argument", *found), Count("argument", *found),
expected expected.display(),
)?; )?;
} }
InconsistentLeadingWhitespace { expected, found } => { InconsistentLeadingWhitespace { expected, found } => {

View File

@ -48,7 +48,7 @@ pub(crate) enum CompileErrorKind<'src> {
FunctionArgumentCountMismatch { FunctionArgumentCountMismatch {
function: &'src str, function: &'src str,
found: usize, found: usize,
expected: usize, expected: Range<usize>,
}, },
InconsistentLeadingWhitespace { InconsistentLeadingWhitespace {
expected: &'src str, expected: &'src str,

View File

@ -106,6 +106,25 @@ impl<'src, 'run> Evaluator<'src, 'run> {
function: *name, function: *name,
message, message,
}), }),
BinaryPlus {
name,
function,
args: ([a, b], rest),
..
} => {
let a = self.evaluate_expression(a)?;
let b = self.evaluate_expression(b)?;
let mut rest_evaluated = Vec::new();
for arg in rest {
rest_evaluated.push(self.evaluate_expression(arg)?);
}
function(&context, &a, &b, &rest_evaluated).map_err(|message| Error::FunctionCall {
function: *name,
message,
})
}
Ternary { Ternary {
name, name,
function, function,

View File

@ -5,6 +5,7 @@ pub(crate) enum Function {
Nullary(fn(&FunctionContext) -> Result<String, String>), Nullary(fn(&FunctionContext) -> Result<String, String>),
Unary(fn(&FunctionContext, &str) -> Result<String, String>), Unary(fn(&FunctionContext, &str) -> Result<String, String>),
Binary(fn(&FunctionContext, &str, &str) -> Result<String, String>), Binary(fn(&FunctionContext, &str, &str) -> Result<String, String>),
BinaryPlus(fn(&FunctionContext, &str, &str, &[String]) -> Result<String, String>),
Ternary(fn(&FunctionContext, &str, &str, &str) -> Result<String, String>), Ternary(fn(&FunctionContext, &str, &str, &str) -> Result<String, String>),
} }
@ -18,7 +19,7 @@ lazy_static! {
("file_name", Unary(file_name)), ("file_name", Unary(file_name)),
("file_stem", Unary(file_stem)), ("file_stem", Unary(file_stem)),
("invocation_directory", Nullary(invocation_directory)), ("invocation_directory", Nullary(invocation_directory)),
("join", Binary(join)), ("join", BinaryPlus(join)),
("just_executable", Nullary(just_executable)), ("just_executable", Nullary(just_executable)),
("justfile", Nullary(justfile)), ("justfile", Nullary(justfile)),
("justfile_directory", Nullary(justfile_directory)), ("justfile_directory", Nullary(justfile_directory)),
@ -42,12 +43,13 @@ lazy_static! {
} }
impl Function { impl Function {
pub(crate) fn argc(&self) -> usize { pub(crate) fn argc(&self) -> Range<usize> {
match *self { match *self {
Nullary(_) => 0, Nullary(_) => 0..0,
Unary(_) => 1, Unary(_) => 1..1,
Binary(_) => 2, Binary(_) => 2..2,
Ternary(_) => 3, BinaryPlus(_) => 2..usize::MAX,
Ternary(_) => 3..3,
} }
} }
} }
@ -127,8 +129,17 @@ fn invocation_directory(context: &FunctionContext) -> Result<String, String> {
.map_err(|e| format!("Error getting shell path: {}", e)) .map_err(|e| format!("Error getting shell path: {}", e))
} }
fn join(_context: &FunctionContext, base: &str, with: &str) -> Result<String, String> { fn join(
Ok(Utf8Path::new(base).join(with).to_string()) _context: &FunctionContext,
base: &str,
with: &str,
and: &[String],
) -> Result<String, String> {
let mut result = Utf8Path::new(base).join(with);
for arg in and {
result.push(arg);
}
Ok(result.to_string())
} }
fn just_executable(_context: &FunctionContext) -> Result<String, String> { fn just_executable(_context: &FunctionContext) -> Result<String, String> {

View File

@ -86,6 +86,18 @@ impl<'src> Node<'src> for Expression<'src> {
tree.push_mut(a.tree()); tree.push_mut(a.tree());
tree.push_mut(b.tree()); tree.push_mut(b.tree());
} }
BinaryPlus {
name,
args: ([a, b], rest),
..
} => {
tree.push_mut(name.lexeme());
tree.push_mut(a.tree());
tree.push_mut(b.tree());
for arg in rest {
tree.push_mut(arg.tree());
}
}
Ternary { Ternary {
name, name,
args: [a, b, c], args: [a, b, c],

View File

@ -2139,7 +2139,7 @@ mod tests {
kind: FunctionArgumentCountMismatch { kind: FunctionArgumentCountMismatch {
function: "arch", function: "arch",
found: 1, found: 1,
expected: 0, expected: 0..0,
}, },
} }
@ -2153,7 +2153,7 @@ mod tests {
kind: FunctionArgumentCountMismatch { kind: FunctionArgumentCountMismatch {
function: "env_var", function: "env_var",
found: 0, found: 0,
expected: 1, expected: 1..1,
}, },
} }
@ -2167,7 +2167,35 @@ mod tests {
kind: FunctionArgumentCountMismatch { kind: FunctionArgumentCountMismatch {
function: "env_var_or_default", function: "env_var_or_default",
found: 1, found: 1,
expected: 2, expected: 2..2,
},
}
error! {
name: function_argument_count_binary_plus,
input: "x := join('foo')",
offset: 5,
line: 0,
column: 5,
width: 4,
kind: FunctionArgumentCountMismatch {
function: "join",
found: 1,
expected: 2..usize::MAX,
},
}
error! {
name: function_argument_count_ternary,
input: "x := replace('foo')",
offset: 5,
line: 0,
column: 5,
width: 7,
kind: FunctionArgumentCountMismatch {
function: "replace",
found: 1,
expected: 3..3,
}, },
} }
} }

View File

@ -2,6 +2,25 @@ use crate::common::*;
pub(crate) trait RangeExt<T> { pub(crate) trait RangeExt<T> {
fn range_contains(&self, i: &T) -> bool; fn range_contains(&self, i: &T) -> bool;
fn display(&self) -> DisplayRange<&Self> {
DisplayRange(self)
}
}
pub(crate) struct DisplayRange<T>(T);
impl Display for DisplayRange<&Range<usize>> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if self.0.start == self.0.end {
write!(f, "{}", self.0.start)?;
} else if self.0.end == usize::MAX {
write!(f, "{} or more", self.0.start)?;
} else {
write!(f, "{} to {}", self.0.start, self.0.end)?;
}
Ok(())
}
} }
impl<T> RangeExt<T> for Range<T> impl<T> RangeExt<T> for Range<T>
@ -53,4 +72,11 @@ mod tests {
assert!((1..=10).range_contains(&10)); assert!((1..=10).range_contains(&10));
assert!((10..=20).range_contains(&15)); assert!((10..=20).range_contains(&15));
} }
#[test]
fn display() {
assert_eq!((1..1).display().to_string(), "1");
assert_eq!((1..2).display().to_string(), "1 to 2");
assert_eq!((1..usize::MAX).display().to_string(), "1 or more");
}
} }

View File

@ -230,6 +230,20 @@ impl Expression {
name: name.lexeme().to_owned(), name: name.lexeme().to_owned(),
arguments: vec![Expression::new(a), Expression::new(b)], arguments: vec![Expression::new(a), Expression::new(b)],
}, },
full::Thunk::BinaryPlus {
name,
args: ([a, b], rest),
..
} => {
let mut arguments = vec![Expression::new(a), Expression::new(b)];
for arg in rest {
arguments.push(Expression::new(arg));
}
Expression::Call {
name: name.lexeme().to_owned(),
arguments,
}
}
full::Thunk::Ternary { full::Thunk::Ternary {
name, name,
args: [a, b, c], args: [a, b, c],

View File

@ -20,6 +20,12 @@ pub(crate) enum Thunk<'src> {
function: fn(&FunctionContext, &str, &str) -> Result<String, String>, function: fn(&FunctionContext, &str, &str) -> Result<String, String>,
args: [Box<Expression<'src>>; 2], args: [Box<Expression<'src>>; 2],
}, },
BinaryPlus {
name: Name<'src>,
#[derivative(Debug = "ignore", PartialEq = "ignore")]
function: fn(&FunctionContext, &str, &str, &[String]) -> Result<String, String>,
args: ([Box<Expression<'src>>; 2], Vec<Expression<'src>>),
},
Ternary { Ternary {
name: Name<'src>, name: Name<'src>,
#[derivative(Debug = "ignore", PartialEq = "ignore")] #[derivative(Debug = "ignore", PartialEq = "ignore")]
@ -56,6 +62,16 @@ impl<'src> Thunk<'src> {
name, name,
}) })
} }
(Function::BinaryPlus(function), 2..=usize::MAX) => {
let rest = arguments.drain(2..).collect();
let b = Box::new(arguments.pop().unwrap());
let a = Box::new(arguments.pop().unwrap());
Ok(Thunk::BinaryPlus {
function: *function,
args: ([a, b], rest),
name,
})
}
(Function::Ternary(function), 3) => { (Function::Ternary(function), 3) => {
let c = Box::new(arguments.pop().unwrap()); let c = Box::new(arguments.pop().unwrap());
let b = Box::new(arguments.pop().unwrap()); let b = Box::new(arguments.pop().unwrap());
@ -85,6 +101,17 @@ impl Display for Thunk<'_> {
Binary { Binary {
name, args: [a, b], .. name, args: [a, b], ..
} => write!(f, "{}({}, {})", name.lexeme(), a, b), } => write!(f, "{}({}, {})", name.lexeme(), a, b),
BinaryPlus {
name,
args: ([a, b], rest),
..
} => {
write!(f, "{}({}, {}", name.lexeme(), a, b)?;
for arg in rest {
write!(f, ", {}", arg)?;
}
write!(f, ")")
}
Ternary { Ternary {
name, name,
args: [a, b, c], args: [a, b, c],

View File

@ -25,6 +25,15 @@ impl<'expression, 'src> Iterator for Variables<'expression, 'src> {
self.stack.push(arg); self.stack.push(arg);
} }
} }
Thunk::BinaryPlus {
args: ([a, b], rest),
..
} => {
let first: &[&Expression] = &[a, b];
for arg in first.iter().copied().chain(rest).rev() {
self.stack.push(arg);
}
}
Thunk::Ternary { args, .. } => { Thunk::Ternary { args, .. } => {
for arg in args.iter().rev() { for arg in args.iter().rev() {
self.stack.push(arg); self.stack.push(arg);

View File

@ -347,3 +347,38 @@ fn trim_start() {
fn trim_end() { fn trim_end() {
assert_eval_eq("trim_end(' f ')", " f"); assert_eval_eq("trim_end(' f ')", " f");
} }
#[test]
#[cfg(not(windows))]
fn join() {
assert_eval_eq("join('a', 'b', 'c', 'd')", "a/b/c/d");
assert_eval_eq("join('a', '/b', 'c', 'd')", "/b/c/d");
assert_eval_eq("join('a', '/b', '/c', 'd')", "/c/d");
assert_eval_eq("join('a', '/b', '/c', '/d')", "/d");
}
#[test]
#[cfg(windows)]
fn join() {
assert_eval_eq("join('a', 'b', 'c', 'd')", "a\\b\\c\\d");
assert_eval_eq("join('a', '\\b', 'c', 'd')", "\\b\\c\\d");
assert_eval_eq("join('a', '\\b', '\\c', 'd')", "\\c\\d");
assert_eval_eq("join('a', '\\b', '\\c', '\\d')", "\\d");
}
#[test]
fn join_argument_count_error() {
Test::new()
.justfile("x := join('a')")
.args(&["--evaluate"])
.stderr(
"
error: Function `join` called with 1 argument but takes 2 or more
|
1 | x := join(\'a\')
| ^^^^
",
)
.status(EXIT_FAILURE)
.run();
}