hcl_edit/template/mod.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
//! Types to represent the HCL template sub-language.
#[cfg(test)]
mod tests;
use crate::encode::{Encode, EncodeState};
use crate::expr::Expression;
use crate::util::{dedent_by, min_leading_whitespace};
use crate::{parser, Decor, Decorate, Decorated, Ident, RawString, Spanned};
use std::fmt;
use std::ops::{Deref, DerefMut, Range};
use std::str::FromStr;
// Re-exported for convenience.
#[doc(inline)]
pub use hcl_primitives::template::Strip;
/// An owning iterator over the elements of a `Template`.
///
/// Values of this type are created by the [`into_iter`] method on [`Template`] (provided by the
/// [`IntoIterator`] trait). See its documentation for more.
///
/// [`into_iter`]: IntoIterator::into_iter
/// [`IntoIterator`]: core::iter::IntoIterator
pub type IntoIter = Box<dyn Iterator<Item = Element>>;
/// An iterator over the elements of a `Template`.
///
/// Values of this type are created by the [`iter`] method on [`Template`]. See its documentation
/// for more.
///
/// [`iter`]: Template::iter
pub type Iter<'a> = Box<dyn Iterator<Item = &'a Element> + 'a>;
/// A mutable iterator over the elements of a `Template`.
///
/// Values of this type are created by the [`iter_mut`] method on [`Template`]. See its
/// documentation for more.
///
/// [`iter_mut`]: Template::iter_mut
pub type IterMut<'a> = Box<dyn Iterator<Item = &'a mut Element> + 'a>;
/// A type representing the HCL template sub-languange in the context of a quoted string literal.
///
/// A template behaves like an expression that always returns a string value. The different
/// elements of the template are evaluated and combined into a single string to return.
#[derive(Debug, Clone, Eq, Default)]
pub struct StringTemplate {
template: Template,
decor: Decor,
}
impl StringTemplate {
/// Constructs a new, empty `StringTemplate`.
#[inline]
pub fn new() -> Self {
StringTemplate::default()
}
/// Constructs a new, empty `StringTemplate` with at least the specified capacity.
#[inline]
pub fn with_capacity(capacity: usize) -> Self {
StringTemplate {
template: Template::with_capacity(capacity),
..Default::default()
}
}
pub(crate) fn despan(&mut self, input: &str) {
self.decor.despan(input);
self.template.despan(input);
}
}
impl From<Vec<Element>> for StringTemplate {
fn from(elements: Vec<Element>) -> Self {
StringTemplate {
template: Template::from(elements),
decor: Decor::default(),
}
}
}
impl PartialEq for StringTemplate {
fn eq(&self, other: &Self) -> bool {
self.template == other.template
}
}
impl Deref for StringTemplate {
type Target = Template;
#[inline]
fn deref(&self) -> &Self::Target {
&self.template
}
}
impl DerefMut for StringTemplate {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.template
}
}
impl<T> Extend<T> for StringTemplate
where
T: Into<Element>,
{
fn extend<I>(&mut self, iterable: I)
where
I: IntoIterator<Item = T>,
{
self.template.extend(iterable);
}
}
impl<T> FromIterator<T> for StringTemplate
where
T: Into<Element>,
{
fn from_iter<I>(iterable: I) -> Self
where
I: IntoIterator<Item = T>,
{
Template::from_iter(iterable).into()
}
}
impl IntoIterator for StringTemplate {
type Item = Element;
type IntoIter = IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.template.into_iter()
}
}
impl<'a> IntoIterator for &'a StringTemplate {
type Item = &'a Element;
type IntoIter = Iter<'a>;
fn into_iter(self) -> Self::IntoIter {
self.template.iter()
}
}
impl<'a> IntoIterator for &'a mut StringTemplate {
type Item = &'a mut Element;
type IntoIter = IterMut<'a>;
fn into_iter(self) -> Self::IntoIter {
self.template.iter_mut()
}
}
/// A heredoc template is introduced by a `<<` sequence and defines a template via a multi-line
/// sequence terminated by a user-chosen delimiter.
#[derive(Debug, Clone, Eq)]
pub struct HeredocTemplate {
/// The delimiter identifier that denotes the heredoc start and end.
pub delimiter: Ident,
/// The raw template contained in the heredoc.
pub template: Template,
indent: Option<usize>,
trailing: RawString,
decor: Decor,
span: Option<Range<usize>>,
}
impl HeredocTemplate {
/// Creates a new `HeredocTemplate` for a delimiter and a template.
pub fn new(delimiter: Ident, template: Template) -> HeredocTemplate {
HeredocTemplate {
delimiter,
template,
indent: None,
trailing: RawString::default(),
decor: Decor::default(),
span: None,
}
}
/// Return the heredoc's indent, if there is any.
pub fn indent(&self) -> Option<usize> {
self.indent
}
/// Set the heredoc's indent.
pub fn set_indent(&mut self, indent: usize) {
self.indent = Some(indent);
}
/// Return a reference to the raw trailing decor before the heredoc's closing delimiter.
pub fn trailing(&self) -> &RawString {
&self.trailing
}
/// Set the raw trailing decor before the heredoc's closing delimiter.
pub fn set_trailing(&mut self, trailing: impl Into<RawString>) {
self.trailing = trailing.into();
}
/// Dedent the heredoc template.
///
/// This will set the heredoc's indent to the number of leading
/// spaces that were stripped off of template string literals, if any.
pub fn dedent(&mut self) {
let stripped_indent = self.template.dedent();
self.indent = stripped_indent;
}
pub(crate) fn despan(&mut self, input: &str) {
self.decor.despan(input);
self.template.despan(input);
self.trailing.despan(input);
}
}
impl PartialEq for HeredocTemplate {
fn eq(&self, other: &Self) -> bool {
self.delimiter == other.delimiter
&& self.template == other.template
&& self.indent == other.indent
&& self.trailing == other.trailing
}
}
/// The main type to represent the HCL template sub-languange.
///
/// A template behaves like an expression that always returns a string value. The different
/// elements of the template are evaluated and combined into a single string to return.
#[derive(Debug, Clone, Eq, Default)]
pub struct Template {
elements: Vec<Element>,
span: Option<Range<usize>>,
}
impl Template {
/// Constructs a new, empty `Template`.
#[inline]
pub fn new() -> Self {
Template::default()
}
/// Constructs a new, empty `Template` with at least the specified capacity.
#[inline]
pub fn with_capacity(capacity: usize) -> Self {
Template {
elements: Vec::with_capacity(capacity),
..Default::default()
}
}
/// Returns `true` if the template contains no elements.
#[inline]
pub fn is_empty(&self) -> bool {
self.elements.is_empty()
}
/// Returns the number of elements in the template, also referred to as its 'length'.
#[inline]
pub fn len(&self) -> usize {
self.elements.len()
}
/// Clears the template, removing all elements.
#[inline]
pub fn clear(&mut self) {
self.elements.clear();
}
/// Returns a reference to the element at the given index, or `None` if the index is out of
/// bounds.
#[inline]
pub fn get(&self, index: usize) -> Option<&Element> {
self.elements.get(index)
}
/// Returns a mutable reference to the element at the given index, or `None` if the index is
/// out of bounds.
#[inline]
pub fn get_mut(&mut self, index: usize) -> Option<&mut Element> {
self.elements.get_mut(index)
}
/// Inserts an element at position `index` within the template, shifting all elements after it
/// to the right.
///
/// # Panics
///
/// Panics if `index > len`.
#[inline]
pub fn insert(&mut self, index: usize, element: impl Into<Element>) {
self.elements.insert(index, element.into());
}
/// Appends an element to the back of the template.
///
/// # Panics
///
/// Panics if the new capacity exceeds `isize::MAX` bytes.
#[inline]
pub fn push(&mut self, element: impl Into<Element>) {
self.elements.push(element.into());
}
/// Removes the last element from the template and returns it, or [`None`] if it is empty.
#[inline]
pub fn pop(&mut self) -> Option<Element> {
self.elements.pop()
}
/// Removes and returns the element at position `index` within the template, shifting all
/// elements after it to the left.
///
/// Like `Vec::remove`, the element is removed by shifting all of the elements that follow it,
/// preserving their relative order. **This perturbs the index of all of those elements!**
///
/// # Panics
///
/// Panics if `index` is out of bounds.
#[inline]
pub fn remove(&mut self, index: usize) -> Element {
self.elements.remove(index)
}
/// An iterator visiting all template elements in insertion order. The iterator element type
/// is `&'a Element`.
#[inline]
pub fn iter(&self) -> Iter<'_> {
Box::new(self.elements.iter())
}
/// An iterator visiting all template elements in insertion order, with mutable references to
/// the values. The iterator element type is `&'a mut Element`.
#[inline]
pub fn iter_mut(&mut self) -> IterMut<'_> {
Box::new(self.elements.iter_mut())
}
/// If the template consists of a single `Element`, returns a reference to it, otherwise
/// `None`.
///
/// # Example
///
/// ```
/// use hcl_edit::template::{Element, Template};
///
/// let mut template = Template::new();
///
/// template.push("one");
///
/// assert_eq!(template.as_single_element(), Some(&Element::from("one")));
///
/// template.push("two");
///
/// assert_eq!(template.as_single_element(), None);
/// ```
pub fn as_single_element(&self) -> Option<&Element> {
match self.len() {
1 => self.get(0),
_ => None,
}
}
/// If the template consists of a single `Element`, returns a mutable reference to it,
/// otherwise `None`.
///
/// # Example
///
/// ```
/// use hcl_edit::template::{Element, Template};
///
/// let mut template = Template::new();
///
/// template.push("one");
///
/// if let Some(element) = template.as_single_element_mut() {
/// *element = Element::from("two");
/// }
///
/// template.push("three");
///
/// assert_eq!(template.as_single_element(), None);
/// assert_eq!(template, Template::from_iter(["two", "three"]));
/// ```
pub fn as_single_element_mut(&mut self) -> Option<&mut Element> {
match self.len() {
1 => self.get_mut(0),
_ => None,
}
}
pub(crate) fn despan(&mut self, input: &str) {
for element in &mut self.elements {
element.despan(input);
}
}
/// Dedents string literals in the template, returning the maximum indent that was stripped,
/// if any.
pub(crate) fn dedent(&mut self) -> Option<usize> {
let mut indent: Option<usize> = None;
let mut skip_first_line = false;
for element in &self.elements {
if let Element::Literal(literal) = element {
if let Some(leading_ws) = min_leading_whitespace(literal, skip_first_line) {
indent = Some(indent.map_or(leading_ws, |indent| indent.min(leading_ws)));
}
skip_first_line = !literal.ends_with('\n');
} else if !skip_first_line {
// Directive or interpolation at line start always mean that no indent can be
// stripped.
return None;
}
}
if let Some(indent) = indent {
skip_first_line = false;
for element in &mut self.elements {
if let Element::Literal(literal) = element {
let dedented = dedent_by(literal, indent, skip_first_line);
*literal.as_mut() = dedented.into();
skip_first_line = !literal.ends_with('\n');
} else if !skip_first_line {
skip_first_line = true;
}
}
}
indent
}
}
impl PartialEq for Template {
fn eq(&self, other: &Self) -> bool {
self.elements == other.elements
}
}
impl fmt::Display for Template {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut state = EncodeState::new(f);
self.encode(&mut state)
}
}
impl FromStr for Template {
type Err = parser::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
parser::parse_template(s)
}
}
impl From<Vec<Element>> for Template {
fn from(elements: Vec<Element>) -> Self {
Template {
elements,
..Default::default()
}
}
}
impl From<Template> for StringTemplate {
fn from(template: Template) -> Self {
StringTemplate {
template,
..Default::default()
}
}
}
impl From<StringTemplate> for Template {
fn from(template: StringTemplate) -> Self {
template.template
}
}
impl<T> Extend<T> for Template
where
T: Into<Element>,
{
fn extend<I>(&mut self, iterable: I)
where
I: IntoIterator<Item = T>,
{
let iter = iterable.into_iter();
let reserve = if self.is_empty() {
iter.size_hint().0
} else {
(iter.size_hint().0 + 1) / 2
};
self.elements.reserve(reserve);
iter.for_each(|v| self.push(v));
}
}
impl<T> FromIterator<T> for Template
where
T: Into<Element>,
{
fn from_iter<I>(iterable: I) -> Self
where
I: IntoIterator<Item = T>,
{
let iter = iterable.into_iter();
let lower = iter.size_hint().0;
let mut template = Template::with_capacity(lower);
template.extend(iter);
template
}
}
impl IntoIterator for Template {
type Item = Element;
type IntoIter = IntoIter;
fn into_iter(self) -> Self::IntoIter {
Box::new(self.elements.into_iter())
}
}
impl<'a> IntoIterator for &'a Template {
type Item = &'a Element;
type IntoIter = Iter<'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a> IntoIterator for &'a mut Template {
type Item = &'a mut Element;
type IntoIter = IterMut<'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}
/// An element of an HCL template.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Element {
/// A literal sequence of characters to include in the resulting string.
Literal(Spanned<String>),
/// An interpolation sequence that evaluates an expression (written in the expression
/// sub-language), and converts the result to a string value.
Interpolation(Interpolation),
/// An `if` or `for` directive that allows for conditional template evaluation.
Directive(Directive),
}
impl Element {
/// Returns `true` if the element represents a literal string.
pub fn is_literal(&self) -> bool {
self.as_literal().is_some()
}
/// If the `Element` is a literal string, returns a reference to it, otherwise `None`.
pub fn as_literal(&self) -> Option<&Spanned<String>> {
match self {
Element::Literal(value) => Some(value),
Element::Interpolation(_) | Element::Directive(_) => None,
}
}
/// Returns `true` if the element represents an interpolation.
pub fn is_interpolation(&self) -> bool {
self.as_interpolation().is_some()
}
/// If the `Element` is an interpolation, returns a reference to it, otherwise `None`.
pub fn as_interpolation(&self) -> Option<&Interpolation> {
match self {
Element::Interpolation(value) => Some(value),
Element::Literal(_) | Element::Directive(_) => None,
}
}
/// Returns `true` if the element represents a directive.
pub fn is_directive(&self) -> bool {
self.as_directive().is_some()
}
/// If the `Element` is a directive, returns a reference to it, otherwise `None`.
pub fn as_directive(&self) -> Option<&Directive> {
match self {
Element::Directive(value) => Some(value),
Element::Literal(_) | Element::Interpolation(_) => None,
}
}
pub(crate) fn despan(&mut self, input: &str) {
match self {
Element::Literal(_) => {}
Element::Interpolation(interp) => interp.despan(input),
Element::Directive(dir) => dir.despan(input),
}
}
}
impl From<&str> for Element {
fn from(value: &str) -> Self {
Element::from(value.to_string())
}
}
impl From<String> for Element {
fn from(value: String) -> Self {
Element::from(Spanned::new(value))
}
}
impl From<Spanned<String>> for Element {
fn from(value: Spanned<String>) -> Self {
Element::Literal(value)
}
}
impl From<Interpolation> for Element {
fn from(value: Interpolation) -> Self {
Element::Interpolation(value)
}
}
impl From<Directive> for Element {
fn from(value: Directive) -> Self {
Element::Directive(value)
}
}
/// An interpolation sequence evaluates an expression (written in the expression sub-language),
/// converts the result to a string value, and replaces itself with the resulting string.
#[derive(Debug, Clone, Eq)]
pub struct Interpolation {
/// The interpolated expression.
pub expr: Expression,
/// The whitespace strip behaviour to use on the template elements preceeding and following
/// after this interpolation sequence.
pub strip: Strip,
span: Option<Range<usize>>,
}
impl Interpolation {
/// Creates a new `Interpolation` from an expression.
pub fn new(expr: impl Into<Expression>) -> Interpolation {
Interpolation {
expr: expr.into(),
strip: Strip::default(),
span: None,
}
}
pub(crate) fn despan(&mut self, input: &str) {
self.expr.despan(input);
}
}
impl PartialEq for Interpolation {
fn eq(&self, other: &Self) -> bool {
self.expr == other.expr && self.strip == other.strip
}
}
/// A template directive that allows for conditional template evaluation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Directive {
/// Represents a template `if` directive.
If(IfDirective),
/// Represents a template `for` directive.
For(ForDirective),
}
impl Directive {
pub(crate) fn despan(&mut self, input: &str) {
match self {
Directive::If(dir) => dir.despan(input),
Directive::For(dir) => dir.despan(input),
}
}
}
impl From<IfDirective> for Directive {
fn from(value: IfDirective) -> Self {
Directive::If(value)
}
}
impl From<ForDirective> for Directive {
fn from(value: ForDirective) -> Self {
Directive::For(value)
}
}
/// The template `if` directive is the template equivalent of the conditional expression, allowing
/// selection of one of two sub-templates based on the condition result.
#[derive(Debug, Clone, Eq)]
pub struct IfDirective {
/// The `if` sub-expression within the directive.
pub if_expr: IfTemplateExpr,
/// The `else` sub-expression within the directive. This is `None` if there is no `else`
/// branch in which case the result string will be empty.
pub else_expr: Option<ElseTemplateExpr>,
/// The `endif` sub-expression within the directive.
pub endif_expr: EndifTemplateExpr,
span: Option<Range<usize>>,
}
impl IfDirective {
/// Creates a new `IfDirective` from the parts for the `if`, `else` and `endif`
/// sub-expressions.
pub fn new(
if_expr: IfTemplateExpr,
else_expr: Option<ElseTemplateExpr>,
endif_expr: EndifTemplateExpr,
) -> IfDirective {
IfDirective {
if_expr,
else_expr,
endif_expr,
span: None,
}
}
pub(crate) fn despan(&mut self, input: &str) {
self.if_expr.despan(input);
if let Some(else_expr) = &mut self.else_expr {
else_expr.despan(input);
}
self.endif_expr.despan(input);
}
}
impl PartialEq for IfDirective {
fn eq(&self, other: &Self) -> bool {
self.if_expr == other.if_expr
&& self.else_expr == other.else_expr
&& self.endif_expr == other.endif_expr
}
}
/// A type representing the `%{ if cond_expr }` sub-expression and the template that follows after
/// it within an [`IfDirective`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IfTemplateExpr {
/// The condition expression.
pub cond_expr: Expression,
/// The template that is included in the result string if the conditional expression evaluates
/// to `true`.
pub template: Template,
/// The whitespace strip behaviour to use on the template elements preceeding and following
/// after the `if` expression.
pub strip: Strip,
preamble: RawString,
}
impl IfTemplateExpr {
/// Creates a new `IfTemplateExpr` for a condition expression and a template.
pub fn new(cond_expr: impl Into<Expression>, template: Template) -> IfTemplateExpr {
IfTemplateExpr {
preamble: RawString::default(),
cond_expr: cond_expr.into(),
template,
strip: Strip::default(),
}
}
/// Return a reference to the raw leading decor after the `if`'s opening `{`.
pub fn preamble(&self) -> &RawString {
&self.preamble
}
/// Set the raw leading decor after the `if`'s opening `{`.
pub fn set_preamble(&mut self, preamble: impl Into<RawString>) {
self.preamble = preamble.into();
}
pub(crate) fn despan(&mut self, input: &str) {
self.preamble.despan(input);
self.cond_expr.despan(input);
self.template.despan(input);
}
}
/// A type representing the `%{ else }` sub-expression and the template that follows after it
/// within an [`IfDirective`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ElseTemplateExpr {
/// The template that is included in the result string if the `if` branch's conditional
/// expression evaluates to `false`.
pub template: Template,
/// The whitespace strip behaviour to use on the template elements preceeding and following
/// after the `else` expression.
pub strip: Strip,
preamble: RawString,
trailing: RawString,
}
impl ElseTemplateExpr {
/// Creates a new `ElseTemplateExpr` for a template.
pub fn new(template: Template) -> ElseTemplateExpr {
ElseTemplateExpr {
preamble: RawString::default(),
trailing: RawString::default(),
template,
strip: Strip::default(),
}
}
/// Return a reference to the raw leading decor after the `else`'s opening `{`.
pub fn preamble(&self) -> &RawString {
&self.preamble
}
/// Set the raw leading decor after the `else`'s opening `{`.
pub fn set_preamble(&mut self, preamble: impl Into<RawString>) {
self.preamble = preamble.into();
}
/// Return a reference to the raw trailing decor before the `else`'s closing `}`.
pub fn trailing(&self) -> &RawString {
&self.trailing
}
/// Set the raw trailing decor before the `else`'s closing `}`.
pub fn set_trailing(&mut self, trailing: impl Into<RawString>) {
self.trailing = trailing.into();
}
pub(crate) fn despan(&mut self, input: &str) {
self.preamble.despan(input);
self.template.despan(input);
self.trailing.despan(input);
}
}
/// A type representing the `%{ endif }` sub-expression within an [`IfDirective`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EndifTemplateExpr {
/// The whitespace strip behaviour to use on the template elements preceeding and following
/// after the `endif` marker.
pub strip: Strip,
preamble: RawString,
trailing: RawString,
}
impl EndifTemplateExpr {
/// Creates a new `EndifTemplateExpr`.
pub fn new() -> EndifTemplateExpr {
EndifTemplateExpr::default()
}
/// Return a reference to the raw leading decor after the `endif`'s opening `{`.
pub fn preamble(&self) -> &RawString {
&self.preamble
}
/// Set the raw leading decor after the `endif`'s opening `{`.
pub fn set_preamble(&mut self, preamble: impl Into<RawString>) {
self.preamble = preamble.into();
}
/// Return a reference to the raw trailing decor before the `endif`'s closing `}`.
pub fn trailing(&self) -> &RawString {
&self.trailing
}
/// Set the raw trailing decor before the `endif`'s closing `}`.
pub fn set_trailing(&mut self, trailing: impl Into<RawString>) {
self.trailing = trailing.into();
}
pub(crate) fn despan(&mut self, input: &str) {
self.preamble.despan(input);
self.trailing.despan(input);
}
}
/// The template `for` directive is the template equivalent of the for expression, producing zero
/// or more copies of its sub-template based on the elements of a collection.
#[derive(Debug, Clone, Eq)]
pub struct ForDirective {
/// The `for` sub-expression within the directive.
pub for_expr: ForTemplateExpr,
/// The `endfor` sub-expression within the directive.
pub endfor_expr: EndforTemplateExpr,
span: Option<Range<usize>>,
}
impl ForDirective {
/// Creates a new `ForDirective` from the parts for the `for` and `endfor` sub-expressions.
pub fn new(for_expr: ForTemplateExpr, endfor_expr: EndforTemplateExpr) -> ForDirective {
ForDirective {
for_expr,
endfor_expr,
span: None,
}
}
pub(crate) fn despan(&mut self, input: &str) {
self.for_expr.despan(input);
self.endfor_expr.despan(input);
}
}
impl PartialEq for ForDirective {
fn eq(&self, other: &Self) -> bool {
self.for_expr == other.for_expr && self.endfor_expr == other.endfor_expr
}
}
/// A type representing the `%{ for key_var, value_var in collection_expr }` sub-expression and
/// the template that follows after it within a [`ForDirective`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ForTemplateExpr {
/// Optional iterator key variable identifier.
pub key_var: Option<Decorated<Ident>>,
/// The iterator value variable identifier.
pub value_var: Decorated<Ident>,
/// The expression that produces the list or object of elements to iterate over.
pub collection_expr: Expression,
/// The template that is included in the result string for each loop iteration.
pub template: Template,
/// The whitespace strip behaviour to use on the template elements preceeding and following
/// after the `for` expression.
pub strip: Strip,
preamble: RawString,
}
impl ForTemplateExpr {
/// Creates a new `ForTemplateExpr` from an optional key variable, value variable, collection
/// expression and template.
pub fn new(
key_var: Option<impl Into<Decorated<Ident>>>,
value_var: impl Into<Decorated<Ident>>,
collection_expr: impl Into<Expression>,
template: Template,
) -> ForTemplateExpr {
ForTemplateExpr {
preamble: RawString::default(),
key_var: key_var.map(Into::into),
value_var: value_var.into(),
collection_expr: collection_expr.into(),
template,
strip: Strip::default(),
}
}
/// Return a reference to the raw leading decor after the `for`'s opening `{`.
pub fn preamble(&self) -> &RawString {
&self.preamble
}
/// Set the raw leading decor after the `for`'s opening `{`.
pub fn set_preamble(&mut self, preamble: impl Into<RawString>) {
self.preamble = preamble.into();
}
pub(crate) fn despan(&mut self, input: &str) {
self.preamble.despan(input);
if let Some(key_var) = &mut self.key_var {
key_var.decor_mut().despan(input);
}
self.value_var.decor_mut().despan(input);
self.collection_expr.despan(input);
self.template.despan(input);
}
}
/// A type representing the `%{ endfor }` sub-expression within a [`ForDirective`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EndforTemplateExpr {
/// The whitespace strip behaviour to use on the template elements preceeding and following
/// after the `endfor` marker.
pub strip: Strip,
preamble: RawString,
trailing: RawString,
}
impl EndforTemplateExpr {
/// Creates a new `EndforTemplateExpr`.
pub fn new() -> EndforTemplateExpr {
EndforTemplateExpr::default()
}
/// Return a reference to the raw leading decor after the `endfor`'s opening `{`.
pub fn preamble(&self) -> &RawString {
&self.preamble
}
/// Set the raw leading decor after the `endfor`'s opening `{`.
pub fn set_preamble(&mut self, preamble: impl Into<RawString>) {
self.preamble = preamble.into();
}
/// Return a reference to the raw trailing decor before the `endfor`'s closing `}`.
pub fn trailing(&self) -> &RawString {
&self.trailing
}
/// Set the raw trailing decor before the `endfor`'s closing `}`.
pub fn set_trailing(&mut self, trailing: impl Into<RawString>) {
self.trailing = trailing.into();
}
pub(crate) fn despan(&mut self, input: &str) {
self.preamble.despan(input);
self.trailing.despan(input);
}
}
decorate_impl! { StringTemplate, HeredocTemplate }
span_impl! {
StringTemplate, HeredocTemplate, Template,
Interpolation, IfDirective, ForDirective
}
forward_span_impl! {
Element => { Literal, Interpolation, Directive },
Directive => { If, For }
}