Allow adding and joining arguments (#5651)

This commit is contained in:
Malo 2025-01-06 16:41:58 +01:00 committed by GitHub
parent 5c876535cc
commit e09b55f00f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 27 additions and 0 deletions

View File

@ -1,4 +1,5 @@
use std::fmt::{self, Debug, Formatter};
use std::ops::Add;
use ecow::{eco_format, eco_vec, EcoString, EcoVec};
use typst_syntax::{Span, Spanned};
@ -376,6 +377,21 @@ impl PartialEq for Args {
}
}
impl Add for Args {
type Output = Self;
fn add(mut self, rhs: Self) -> Self::Output {
self.items.retain(|item| {
!item.name.as_ref().is_some_and(|name| {
rhs.items.iter().any(|a| a.name.as_ref() == Some(name))
})
});
self.items.extend(rhs.items);
self.span = Span::detached();
self
}
}
/// An argument to a function call: `12` or `draw: false`.
#[derive(Clone, Hash)]
#[allow(clippy::derived_hash_with_manual_eq)]

View File

@ -36,6 +36,7 @@ pub fn join(lhs: Value, rhs: Value) -> StrResult<Value> {
(Symbol(a), Content(b)) => Content(TextElem::packed(a.get()) + b),
(Array(a), Array(b)) => Array(a + b),
(Dict(a), Dict(b)) => Dict(a + b),
(Args(a), Args(b)) => Args(a + b),
(a, b) => mismatch!("cannot join {} with {}", a, b),
})
}
@ -136,6 +137,7 @@ pub fn add(lhs: Value, rhs: Value) -> HintedStrResult<Value> {
(Array(a), Array(b)) => Array(a + b),
(Dict(a), Dict(b)) => Dict(a + b),
(Args(a), Args(b)) => Args(a + b),
(Color(color), Length(thickness)) | (Length(thickness), Color(color)) => {
Stroke::from_pair(color, thickness).into_value()

View File

@ -16,3 +16,12 @@
#let args = arguments(0, 1, a: 2, 3)
// Error: 2-14 arguments do not contain key "b" and no default value was specified
#args.at("b")
--- arguments-plus-sum-join ---
#let lhs = arguments(0, "1", key: "value", 3)
#let rhs = arguments(other-key: 4, key: "other value", 3)
#let result = arguments(0, "1", 3, other-key: 4, key: "other value", 3)
#test(lhs + rhs, result)
#test({lhs; rhs}, result)
#test((lhs, rhs).sum(), result)
#test((lhs, rhs).join(), result)