1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-29 12:07:46 +00:00

Merge pull request #2693 from thomasqueirozb/expr_uresult

expr: use UResult
This commit is contained in:
Sylvestre Ledru 2021-09-26 16:14:17 +02:00 committed by GitHub
commit df42fed3b3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -9,6 +9,7 @@
extern crate uucore; extern crate uucore;
use clap::{crate_version, App, Arg}; use clap::{crate_version, App, Arg};
use uucore::error::{UResult, USimpleError};
use uucore::InvalidEncodingHandling; use uucore::InvalidEncodingHandling;
mod syntax_tree; mod syntax_tree;
@ -23,7 +24,8 @@ pub fn uu_app() -> App<'static, 'static> {
.arg(Arg::with_name(HELP).long(HELP)) .arg(Arg::with_name(HELP).long(HELP))
} }
pub fn uumain(args: impl uucore::Args) -> i32 { #[uucore_procs::gen_uumain]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let args = args let args = args
.collect_str(InvalidEncodingHandling::ConvertLossy) .collect_str(InvalidEncodingHandling::ConvertLossy)
.accept_any(); .accept_any();
@ -32,13 +34,13 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
// The following usage should work without escaping hyphens: `expr -15 = 1 + 2 \* \( 3 - -4 \)` // The following usage should work without escaping hyphens: `expr -15 = 1 + 2 \* \( 3 - -4 \)`
if maybe_handle_help_or_version(&args) { if maybe_handle_help_or_version(&args) {
0 Ok(())
} else { } else {
let token_strings = args[1..].to_vec(); let token_strings = args[1..].to_vec();
match process_expr(&token_strings) { match process_expr(&token_strings) {
Ok(expr_result) => print_expr_ok(&expr_result), Ok(expr_result) => print_expr_ok(&expr_result),
Err(expr_error) => print_expr_error(&expr_error), Err(expr_error) => Err(USimpleError::new(2, &expr_error)),
} }
} }
} }
@ -49,19 +51,15 @@ fn process_expr(token_strings: &[String]) -> Result<String, String> {
evaluate_ast(maybe_ast) evaluate_ast(maybe_ast)
} }
fn print_expr_ok(expr_result: &str) -> i32 { fn print_expr_ok(expr_result: &str) -> UResult<()> {
println!("{}", expr_result); println!("{}", expr_result);
if expr_result == "0" || expr_result.is_empty() { if expr_result == "0" || expr_result.is_empty() {
1 Err(1.into())
} else { } else {
0 Ok(())
} }
} }
fn print_expr_error(expr_error: &str) -> ! {
crash!(2, "{}", expr_error)
}
fn evaluate_ast(maybe_ast: Result<Box<syntax_tree::AstNode>, String>) -> Result<String, String> { fn evaluate_ast(maybe_ast: Result<Box<syntax_tree::AstNode>, String>) -> Result<String, String> {
maybe_ast.and_then(|ast| ast.evaluate()) maybe_ast.and_then(|ast| ast.evaluate())
} }