From e12d7fc914a1c97376ed112a92326a138fa2b3f8 Mon Sep 17 00:00:00 2001 From: Basile Henry Date: Sun, 1 Nov 2020 10:21:53 +0100 Subject: Allow `Text/replace ` to support an abstract haystack --- dhall/src/builtins.rs | 50 ++++++++++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 22 deletions(-) (limited to 'dhall/src') diff --git a/dhall/src/builtins.rs b/dhall/src/builtins.rs index 41a9f75..cc426dd 100644 --- a/dhall/src/builtins.rs +++ b/dhall/src/builtins.rs @@ -418,30 +418,36 @@ fn apply_builtin(b: Builtin, args: Vec, env: NzEnv) -> NirKind { } } - // The needle and the haystack need to be fully - // evaluated as Text otherwise no progress can be made - match (nir_to_string(needle), nir_to_string(haystack)) { - (Some(n), Some(h)) => { - // When the needle is empty the haystack is returned untouched - if n.is_empty() { - Ret::Nir(haystack.clone()) - // Fast case when replacement is fully evaluated - } else if let Some(r) = nir_to_string(replacement) { - Ret::Nir(Nir::from_text(h.replace(&n, &r))) - } else { - use itertools::Itertools; + // The needle needs to be fully evaluated as Text otherwise no + // progress can be made + match nir_to_string(needle) { + // When the needle is empty the haystack is returned untouched + Some(n) if n.is_empty() => Ret::Nir(haystack.clone()), + Some(n) => { + // The haystack needs to be fully evaluated as Text otherwise no + // progress can be made + if let Some(h) = nir_to_string(haystack) { + // Fast case when replacement is fully evaluated + if let Some(r) = nir_to_string(replacement) { + Ret::Nir(Nir::from_text(h.replace(&n, &r))) + } else { + use itertools::Itertools; - let parts = h.split(&n).map(|s| { - InterpolatedTextContents::Text(s.to_string()) - }); - let replacement = - InterpolatedTextContents::Expr(replacement.clone()); + let parts = h.split(&n).map(|s| { + InterpolatedTextContents::Text(s.to_string()) + }); + let replacement = InterpolatedTextContents::Expr( + replacement.clone(), + ); - Ret::Nir(Nir::from_kind(NirKind::TextLit( - nze::nir::TextLit::new( - parts.intersperse(replacement), - ), - ))) + Ret::Nir(Nir::from_kind(NirKind::TextLit( + nze::nir::TextLit::new( + parts.intersperse(replacement), + ), + ))) + } + } else { + Ret::DoneAsIs } } _ => Ret::DoneAsIs, -- cgit v1.2.3