Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

expr: short-circuit evaluation for & #5402

Merged
merged 2 commits into from
Oct 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 19 additions & 9 deletions src/uu/expr/src/syntax_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,16 +166,26 @@ impl AstNode {
{
let mut out = Vec::with_capacity(operands.len());
let mut operands = operands.iter();
// check the first value before `|`, stop evaluate and return directly if it is true.
// push dummy to pass the check of `len() == 2`
if op_type == "|" {
if let Some(value) = operands.next() {
let value = value.evaluate()?;
out.push(value.clone());
if value_as_bool(&value) {
out.push(String::from("dummy"));
return Ok(out);

if let Some(value) = operands.next() {
let value = value.evaluate()?;
out.push(value.clone());
// short-circuit evaluation for `|` and `&`
// push dummy to pass `assert!(values.len() == 2);`
match op_type.as_ref() {
"|" => {
if value_as_bool(&value) {
out.push(String::from("dummy"));
return Ok(out);
}
}
"&" => {
if !value_as_bool(&value) {
out.push(String::from("dummy"));
return Ok(out);
}
}
_ => {}
}
}

Expand Down
15 changes: 15 additions & 0 deletions tests/by-util/test_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,21 @@ fn test_and() {
.args(&["-14", "&", "1"])
.run()
.stdout_is("-14\n");

new_ucmd!()
.args(&["0", "&", "a", "/", "5"])
.run()
.stdout_only("0\n");

new_ucmd!()
.args(&["", "&", "a", "/", "5"])
.run()
.stdout_only("0\n");

new_ucmd!()
.args(&["-1", "&", "10", "/", "5"])
.succeeds()
.stdout_only("-1\n");
}

#[test]
Expand Down
Loading