Mutable methods with return values

This commit is contained in:
Laurenz 2022-12-21 23:48:04 +01:00
parent 038f9b015e
commit 1eda162867
4 changed files with 13 additions and 11 deletions

View File

@ -93,15 +93,14 @@ impl Array {
}
/// Remove and return the value at the specified index.
pub fn remove(&mut self, index: i64) -> StrResult<()> {
pub fn remove(&mut self, index: i64) -> StrResult<Value> {
let len = self.len();
let i = self
.locate(index)
.filter(|&i| i < self.0.len())
.ok_or_else(|| out_of_bounds(index, len))?;
Arc::make_mut(&mut self.0).remove(i);
Ok(())
Ok(Arc::make_mut(&mut self.0).remove(i))
}
/// Extract a contigous subregion of the array.

View File

@ -79,10 +79,10 @@ impl Dict {
Arc::make_mut(&mut self.0).insert(key, value);
}
/// Remove a mapping by `key`.
pub fn remove(&mut self, key: &str) -> StrResult<()> {
/// Remove a mapping by `key` and return the value.
pub fn remove(&mut self, key: &str) -> StrResult<Value> {
match Arc::make_mut(&mut self.0).remove(key) {
Some(_) => Ok(()),
Some(value) => Ok(value),
None => Err(missing_key(key)),
}
}

View File

@ -816,7 +816,7 @@ impl Eval for ast::MethodCall {
let result = if methods::is_mutating(&method) {
let args = self.args().eval(vm)?;
let value = self.target().access(vm)?;
methods::call_mut(value, &method, args, span).map(|()| Value::None)
methods::call_mut(value, &method, args, span)
} else {
let value = self.target().eval(vm)?;
let args = self.args().eval(vm)?;

View File

@ -128,9 +128,10 @@ pub fn call_mut(
method: &str,
mut args: Args,
span: Span,
) -> SourceResult<()> {
) -> SourceResult<Value> {
let name = value.type_name();
let missing = || Err(missing_method(name, method)).at(span);
let mut output = Value::None;
match value {
Value::Array(array) => match method {
@ -139,12 +140,14 @@ pub fn call_mut(
"insert" => {
array.insert(args.expect("index")?, args.expect("value")?).at(span)?
}
"remove" => array.remove(args.expect("index")?).at(span)?,
"remove" => output = array.remove(args.expect("index")?).at(span)?,
_ => return missing(),
},
Value::Dict(dict) => match method {
"remove" => dict.remove(&args.expect::<EcoString>("key")?).at(span)?,
"remove" => {
output = dict.remove(&args.expect::<EcoString>("key")?).at(span)?
}
_ => return missing(),
},
@ -152,7 +155,7 @@ pub fn call_mut(
}
args.finish()?;
Ok(())
Ok(output)
}
/// Whether a specific method is mutating.